开发者

finding order of selected div with .eq

开发者 https://www.devze.com 2023-03-01 22:10 出处:网络
I have the following HTML: <div id=\"MyDiv\"> <div class=\"MyClass\">test1</div> <div class=\"MyClass\">test2&开发者_开发百科lt;/div>

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

精彩评论

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