在列表中查找元素的位置 [英] Find the position of an element within a list
本文介绍了在列表中查找元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找使用jQuery在列表中单击元素的位置(即顺序).
I'm looking to find the position (i.e. the order) of a clicked element within a list using jQuery.
我有:
<ul>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
...
</ul>
单击<li>
时,我要将其位置存储在变量中.例如,如果我单击元素3,则"3"将存储在变量中.
On click of an <li>
, I want to store it's position within a variable. For example, if I clicked on Element 3, then "3" would be stored in a variable.
这怎么实现?
非常感谢您的帮助!
推荐答案
使用 index()
:
$("li").click(function() {
var index = $(this).parent().children().index(this);
alert("You clicked item " + index);
});
索引从0开始.
这篇关于在列表中查找元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文