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()
.
精彩评论