I have the following jQuery script and I am needing to modify it to allow me to filter the text in the menu item titles and insert a <br>
after the first word if there are only two words in the title or after the second word if there are three or more words in the title. I have attached a screenshot of the design prototype showing how the menu items should display.
我有以下jQuery脚本,我需要修改它以允许我过滤菜单项标题中的文本,并在第一个单词后插入一个
如果标题中只有两个单词或在第二个单词后面标题中有三个或更多单词。我附上了设计原型的屏幕截图,显示了菜单项应该如何显示。
(function($){
$(document).ready(function(){
var node = $("#navigation li a").contents().filter(function () { return this.nodeType == 3 }).first(),
text = node.text(),
first = text.slice(0, text.indexOf(" "));
if (!node.length)
return;
node[0].nodeValue = text.slice(first.length);
node.before(first + '<br/>');
});
})(jQuery);
1 个解决方案
#1
2
Please have a look at below approach:
请看下面的方法:
(function($) {
$(document).ready(function() {
$("#navigation li a").each(function() {
var text = $(this).text();
var wordArray = text.split(" ");
if (wordArray.length == 2) {
$(this).html(wordArray.join('</br>'));
} else if (wordArray.length > 2) {
$(this).html(wordArray.slice(0, 2).join(' ') + '</br>' + wordArray.slice(2).join(' '));
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="navigation">
<li><a>First Menu</a>
</li>
<li><a>Two Words</a>
</li>
<li><a>More Than Two</a>
</li>
<li><a>More Than Four Words In Menu</a>
</li>
</ul>
Here we are iterating over all the <a>
tags which are part of our navigation menu and simply we are fetching their text to check length of it.
在这里,我们迭代所有标签,这些标签是导航菜单的一部分,我们只是提取文本来检查它的长度。
#1
2
Please have a look at below approach:
请看下面的方法:
(function($) {
$(document).ready(function() {
$("#navigation li a").each(function() {
var text = $(this).text();
var wordArray = text.split(" ");
if (wordArray.length == 2) {
$(this).html(wordArray.join('</br>'));
} else if (wordArray.length > 2) {
$(this).html(wordArray.slice(0, 2).join(' ') + '</br>' + wordArray.slice(2).join(' '));
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="navigation">
<li><a>First Menu</a>
</li>
<li><a>Two Words</a>
</li>
<li><a>More Than Two</a>
</li>
<li><a>More Than Four Words In Menu</a>
</li>
</ul>
Here we are iterating over all the <a>
tags which are part of our navigation menu and simply we are fetching their text to check length of it.
在这里,我们迭代所有标签,这些标签是导航菜单的一部分,我们只是提取文本来检查它的长度。