How to get the eq() of $(this)?
Here's my code:
$('div.menu > ul > li > a').click(function(e) {
alert($(this).eq());
e.preventDefau开发者_StackOverflow社区lt();
});
<div class="menu">
<ul>
<li><a href="">Animals</a></li>
<li><a href="">Cars</a></li>
<li><a href="">Sports</a></li>
</ul>
</div><!-- menu -->
My attempt alerts an object object error. If should instead return the numeric place of the link being clicked. For example if you click animals it should alert 1 (not sure if the eq count starts at 0 like arrays in which case it should alert that) and if you click sports it should alert 3 and so on...
Eq does start at 0, and to get it you need to have a reference list, try:
var links = $('div.menu > ul > li > a');
links.click(function(e) {
var index = links.index($(this));
alert(index);
e.preventDefault();
});
Online example: http://jsfiddle.net/tYeV4/
The function you're after is $(this).index()
, and it's zero-based.
You can make the functionality simpler by using the zero argument version of .index()
, and putting the handler on the <li>
tags instead of the <a>
tags - see http://jsfiddle.net/udKJf/
$('div.menu > ul > li').click(function(e) {
alert($(this).index());
e.preventDefault();
});
Putting the handler on the <li>
tags allows a sibling-based index to be automatically calculated by jQuery.
Alternatively, leave the selector referring to the <a>
tags and use $(this).parent().index()
.
精彩评论