I was wondering how to get the index of span with content itemEleven, with jquery in the following case. Assuming that we aren't able to get element by content value:
<div>
<span class="itemSubMenu">itemOne</span>
<span class="itemSubMenu">itemTwo</span>
<span class="itemSubMenu">itemThree</span>
<span class="itemSubMenu">itemFour</span>
<span class="itemSubMenu">itemFive</span>
<span class="itemSubMenu">itemSix</span>
<span class="itemSubMenu">itemSeven</span>
</div>
<div>
<span class="subMenuitemSubMenu">Something</span>
<span class="subMenuitemSubMenu">Somethi开发者_如何学编程ng too</span>
</div>
<div>
<span class="itemSubMenu">itemEight</span>
<span class="itemSubMenu">itemNine</span>
<span class="itemSubMenu">itemTen</span>
<span class="itemSubMenu">itemEleven</span>
<span class="itemSubMenu">itemTwelve</span>
<span class="itemSubMenu">itemThirteen</span>
<span class="itemSubMenu">itemFourteen</span>
<span class="itemSubMenu">itemFifteen</span>
</div>
When i try to get, for example, itemEight with the following method.
$(".itemSubmenu").click(function(){
alert($(this).index());
});
It alerts 0, instead 9. Assuming that it is zero-based-index.
Have you tried
$(".itemSubMenu").index($(this));
inside of the click event?
Here is a fiddle for you: http://jsfiddle.net/3mDK5/
Index is always based on its index within its parent.
You'll need to do this:
$(".itemSubMenu").click(function() {
alert($(this).parent().parent().find('span').index(this));
});
But really you'd want some sort of contextual selector to base it off of:
$(".itemSubMenu").click(function() {
alert($('#foo').find('span').index(this));
});
Fiddle: http://jsfiddle.net/THyAB/
You would need to get the collection of spans with class itemSubMenu
and then get the index of this
from that collection to get the correct index.
var selected = $(this);
var myIndex = $("itemSubMenu").index(selected);
Demo
I like this method.
$(".itemSubMenu").click(function(){
var $this = this;
var i;
$(".itemSubMenu").each(function(idx,val){
if(val === $this) console.log(i = idx);
})
});
精彩评论