jQuery finding 'nth-child' value
I have a ul set up as navigation, which I'll be animating on hover.
As all the nav items are different widths, I'll be storing their default widths in an Array, so that on hover out, these widths can be passed back in to the animate method.
What I need is a way to find what 'nth-child' the element is in order to retrieve the correct width from the array.
Something like:
var count = $(this).count(); //obviously this isn't right!
So that then I can do:
开发者_如何学运维$(this).animate({'width':array(count)}, 400);
Any suggestions would help me a lot - and if there's a better way to do this kind of thing I'd gladly accept pointers!
I think index
is what you're looking for. It tells you where an element is relative to its siblings, e.g., the second element within the parent is index 1. You can use selectors so you only consider certain siblings and not others, etc.
if you really want to store the last width, use .data()
in each <li>
something like
$('ul li').css('width', function(i,v){
$(this).data('lastWidth',v);
return v;
})
then something like,
$('li').animate({'width': $(this).data('lastWidth') }, 400);
this is a rough example but I guess it's better than array... in this way, you are sure each <li> is holding the right value....
html like this
<ul id="ul">
<li style="width: 50px;">1</li>
<li style="width: 75px;">2</li>
<li style="width: 100px;">3</li>
</ul>
and script like this
$(function(){
arrayOfWidth = [];
liItems = $('#ul li');
someLi = $('#ul li:eq(1)'); // just for example
liItems.each(function(index, domElement){
var $this = $(domElement);
arrayOfWidth.push($this.width());
});
alert(getWidth(someLi));
});
function getWidth(li){
var index = liItems.index(li);
return arrayOfWidth[index];
}
精彩评论