大佬教程收集整理的这篇文章主要介绍了jQuery.each – 将li元素放入ul中,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<div class="phrase"> <ul class="items"> <li class="agap"><ul><li>TEXT1</li></ul></li> <li class="agap"><ul> </ul></li> <!-- empty ul --> <li class="aword">TEXT2</li> .. </ul> </div> <div class="phrase"> ... </div>
我想获取每个“短语”文本变量中“项目”中的所有元素,如下所示:
var string = "TEXT1 - BLANK - TEXT2";
我目前有这个JavaScript代码:
<script> $(function() { $('.phrase .items').each(function(){ var myText = ""; // At this point I need to loop all li items and get the text inside // depending on the class attribute alert(myText); }); }; </script>
如何迭代所有< li>里面的。
我正在尝试不同的方式,但我没有得到好的结果。
// note this array has outer scope var phrases = []; $('.phrase').each(function(){ // this is inner scope,in reference to the .phrase element var phrase = ''; $(this).find('li').each(function(){ // cache jquery var var current = $(this); // check if our current li has children (sub elements) // if it does,skip it // ps,you can work with this by seeing if the first child // is a UL with blank inside and odd your custom BLANK text if(current.children().size() > 0) {return true;} // add current text to our current phrase phrase += current.text(); }); // Now that our current phrase is completely build we add it to our outer array phrases.push(phrase); }); // note the comma in the alert shows separate phrases alert(phrases);
工作jsfiddle。
有一件事是,如果你得到上层的.text(),你将得到所有的子级文本。
保留数组将允许提取许多多个短语。
编辑:
这样应该能够更好地使用空的UL,而不需要LI:
// outer scope var phrases = []; $('.phrase').each(function(){ // inner scope var phrase = ''; $(this).find('li').each(function(){ // cache jquery object var current = $(this); // check for sub levels if(current.children().size() > 0) { // check is sublevel is just empty UL var emptyULtest = current.children().eq(0); if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){ phrase += ' -BLANK- '; //custom blank text return true; } else { // else it is an actual sublevel with li's return true; } } // if it gets to here it is actual li phrase += current.text(); }); phrases.push(phrase); }); // note the comma to separate multiple phrases alert(phrases);
以上是大佬教程为你收集整理的jQuery.each – 将li元素放入ul中全部内容,希望文章能够帮你解决jQuery.each – 将li元素放入ul中所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。