How to get the index of list Items on click of li using jquery
Is there开发者_如何学Go a way through which I can get the index of list Items on click of li
element using JavaScript/jQuery?
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
$('ul li').click(function(){ alert($(this).index()); });
Use the onClick event to call the function getIndex (no jQuery needed, just vanilla javascript):
onClick = "getIndex(this);"
function getIndex(node) {
var childs = node.parentNode.childNodes;
for (i = 0; i < childs.length; i++) {
if (node == childs[i]) break;
}
return i;
}
Index will start beginning with 0! To let it start with 1 : return i+1
精彩评论