jQuery eq() loop

2019-09-12 03:33发布

问题:

can you help me with this?

$(document).ready(function(){
     $("ul.fam:eq(0) li:eq(2)").addClass("redbold");    
});

In this code, is there a way to loop or increment the '0' value in -> $("ul.fam:eq(0) ? Like making it 0,1,2,3,4,5 and so on... and stop the loop for example when it reaches '3'

Thank you.

回答1:

You can use the :lt() (less than index) selector, like this:

$(document).ready(function(){
  $("ul.fam:lt(4) > li:nth-child(3)").addClass("redbold");    
});

You can test it out here.

This will be the same as selecting :eq(0) through :eq(3). There's also a :gt() selector for the other way around...you can combine both or .slice() to get a range.



回答2:

Loops are sometimes necessary, but buddy Nick Craver probably has the easier answer. Anyway, this is exactly what you asked for.

$(function(){
    for(i=0;i<=2;i++){
     $("ul.fam:eq("+i+") li:eq(2)").addClass("redbold");    
    }
});