开发者

finding order of selected div with .eq

I have the following HTML:

<div id="MyDiv">

  <div class="MyClass">test1</div>
  <div class="MyClass">test2&开发者_开发百科lt;/div>
  <div class="MyClass">test3</div>
  <div class="MyClass">test4</div>

</div>

When I click on a MyClass element, I need to return the element's order in TheIndex

$('.MyClass').click (function (){
 var TheIndex = ?
 alert(TheIndex);
});

For instance, if the user clicks on test2, it needs to return 2 because it's the second element.

Thanks for your suggestions.


You could use:

$('.MyClass').click(
    function(){
        alert($(this).index());
    });

JS Fiddle.

Bearing in mind that JavaScript uses zero-based arrays, so clicking on 'test2' will alert the value of '1', rather than '2'. To amend this, you could simply increment the value by 1:

$('.MyClass').click(
    function(){
        alert(($(this).index()) + 1);
    });

JS Fiddle.


Reference:

  • index().
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜