Modifying nth li in a list using jquery
I'm trying something very basic, but I just can't figure out why this won't work. I can get information on the object using [i] but I can't change data this way?
// Make all the li's invisible
$('div#rotator ul li').css({opacity: 0.0});
// Calculate a random number between 1 and 3
var randnr = Math.floor((1-4)*Math.random()) + 4;
for(var i = 0; i < $('#rotator ul li开发者_StackOverflow').length; i++) {
// Make the i element appear
$('#rotator ul li')[i].css({opacity: 1.0});
}
jQuery objects are array-like objects that can be used as an array of raw DOM elements.
Therefore, $(...)[i]
gets the i'th raw DOM element, not a jQuery object containing it.
To get a jQuery object containing the i'th element, call the .eq()
method, like this:
$('#rotator ul li').eq(i).css({opacity: 1.0});
You can also use the :eq
selector:
$('#rotator ul li:eq(i)').css({opacity: 1.0});
However, you don't need a loop at all; you can hide all of the elements at once:
$('div#rotator ul li').css({opacity: 1.0});
You are getting this problem because when you use array indices you get a DOM element and css()
is a method on a jQuery object. So you can do:
$($("#rotator ul li")[i]).css("opacity", 1.0);
Of course that's awkward so you can use eq()
:
$("#rotator ul li").eq(i).css("opacity", 1.0);
But you're doing that change in all elements in the set so a simpler solution than a loop is to simply do:
$("#rotator ul li").css("opacity", 1.0);
That will apply the CSS to all elements in the jQuery object.
精彩评论