简体   繁体   English

如何使用JQuery嵌套for-each循环以获取特定的li元素?

[英]How do I do a nested for-each loop with JQuery to get specific li elements?

What I'm trying to do is essentially go through ul s which are organized like 我正在尝试做的基本上是通过有组织的ul

<ul class="some-ul">
    <li class="some-li"></li>
    <li></li>    
    <li></li>
    <li class="some-li"></li>
</ul> 
<ul class="some-ul">
    <li class="some-li"></li>
    <li></li>    
    <li></li>
    <li></li>
</ul> 
<ul class="some-ul">
    <li class="some-li"></li>
    <li class="some-li"></li>    
    <li class="some-li"></li>
    <li class="some-li"></li>
</ul> 

and do something with the li s of class some-li and something else with the li s that don't have that class. 和做的事情li类第some-li ,并与别的东西li没有该类秒。 So, it would be equivalent to 所以,它等同于

$('ul.some-class li.some-class').each(function() {
   // do something
});

$('ul.some-class li:not(.some-class)').each(function() {
   // do something else
});

except I want to do it like 除了我想这样做

$('ul.some-class').each(function() {
     // loop through the list elements of this list 
});

but I don't know how to construct that inner loop. 但我不知道如何构建内循环。 Is this possible, and if so, what tool should I using? 这是可能的,如果是这样,我应该使用什么工具?

Within .each , this will be the current element of the iteration. .eachthis将是迭代的当前元素。 You can then use $(this).find() to find elements within it: 然后,您可以使用$(this).find()来查找其中的元素:

$('ul.some-ul').each(function(i, ul) {
    $(ul).find("li").each(function(j, li) {
        // Now you can use $(ul) and $(li) to refer to the list and item
        if ($(li).hasClass('some-li')) {
            ...
        }
    });
});

You can use hasClass and a CSS selector to get all immediate children (The <li> s) . 您可以使用hasClass和CSS选择器来获取所有直接子项<li> s)

$('ul.some-class > li').each(function() {
     if ($(this).hasClass('some-class')) {
         //Do something
     } else {
         //Do something else
     }
});

Loop through all the <li> and use hasClass() to see if they fit the class you want or not and react accordingly 循环遍历所有<li>并使用hasClass()来查看它们是否适合您想要的类,并做出相应的反应

$('.some-ul').children().each(function(){
   // "this" is current li
   if ( $(this).hasClass('some-li') ){
       $(this).doSomeClassThing();
   } else {
        $(this).doNoClassThing();
   }    
});

One pass through and you are done 一次通过,你就完成了

The callback of the each call gets the index and the element as arguments. 每次调用的回调都将索引和元素作为参数。

This way you can 这样你就可以

$('ul.some-class').each(function(i, elt) { 
     $(elt, 'li.some-class').each ...
 });

https://api.jquery.com/jquery.each/ https://api.jquery.com/jquery.each/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM