Jquery :eq() selector not working for me
Here is what I'm trying to do:
$(document).ready(function(){
$('ul li:eq(3n+1)').css({backgroundColor:'#f00'});
});
HT开发者_如何学JAVAML
<ul>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
</ul>
http://jsfiddle.net/mD6Hf/2/
Because you seem to have confused jQuery's eq()
selector with CSS' :nth-child()
pseudo-selector.
To use a CSS selector for this (albeit in the context of jQuery):
$(document).ready(function(){
$('ul li:nth-child(3n+1)').css({backgroundColor:'#f00'});
});
JS Fiddle demo
Using filter()
you can use:
$('li').filter(
function(i){
if (i%3 + 1 == 1){
return $(this);
}
}).css('background-color','#f00');
JS Fiddle demo.
But I can't see how to do it with eq()
since, so far as I can see, that's meant to return only one result (though I've not exhaustively read the whole jQuery API).
References:
:nth-child selector()
.filter()
.
Or if you want to use :eq() then try it this way:
$('ul li:eq(3)').css({backgroundColor:'#f00'});
:eq() is 0-based. Means that index 3 is the fourth element.
Here's one solution that uses a little more jQuery to do the job:
$(document).ready(function(){
$('ul li').each(function(i,el) {
if (i%3==0)
$(this).css({backgroundColor:'#f00'});
})
});
http://jsfiddle.net/mD6Hf/6/
This will work even if the browser doesn't support CSS3.
精彩评论