why the code add 1 to the length?
the link: http://www.mind4m.com/stories.php?pageid=10
what's this line meaning?
var curChildIndex = $(this).parent().prevAll().length + 1;
select all the li label before the current a label the add one? am i right? but why it开发者_如何学C adds one?
$(this).parent().children('div:nth-child('+curChildIndex+')')
.fadeIn('normal',function() {
$(this).addClass('current');
});
i can't understand this well. could i write this part to children('div:nth-child(curChildIndex)')
It adds one because the :nth-child
selector is one based, not zero based.
If you obtained an array of all of the children, the first one would be the zeroth element in the array.
However to access that same element via CSS you'd use :nth-child(1)
.
See http://api.jquery.com/nth-child-selector/
An alternative implementation might be (untested):
var curChildIndex = $(this).parent().prevAll().length;
$(this).parent().children('div')
.eq(curChildIndex)
.fadeIn('normal',function() {
$(this).addClass('current');
});
But this will only work correctly if all of the child elements are <div>
elements.
The variable curChildIndex
is used in the selector nth-child
. It's computed by counting all the previous siblings (prevAll().length
) and then adding 1 to get to the current index. Note that the first child has index 1 when using nth-child
.
Example: If the current element is the fourth element of the parent node, then prevAll()
will return an array of length 3. The code then adds 1 to get the correct index 4.
精彩评论