使用jQuery识别在多级列表中单击了哪个项目 [英] identifying which item is clicked in a multi level list using jquery
问题描述
我的html看起来像这样
my html looks like this
<div class="row1">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="row2">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="row3">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
这是我的jquery,用于获取点击项的索引:
here's my jquery to get the index of clicked item:
$('li').click(function(){
var ind = $(this).index();
alert(ind);
});
这会提醒单击的项目索引.但是,第1行,第2行和第3行的项目1具有相同的索引.与item2和item3相同.这一点我可以理解,因为它属于不同的ul.正在考虑为3 ul创建不同的点击侦听器.但是我在考虑你们是否有一个更好的主意,那就是为所有可以创建连续索引号的所有对象创建一个监听器.
This alerts the index of item clicked. However, items 1 of row1, row2 and row3 have the same index. Same with item2 and item3. This, I can understand because it belongs to different ul. Am thinking of creating different click listeners for 3 ul. But am thinking whether you guys have a better idea to create one listener for all that would give continous index number for all items.
谢谢.
推荐答案
您需要跟踪<li>
元素的列表,然后使用它来确定索引:
You need to keep track of the list of <li>
elements and then use that to determine the index:
var $all_lis = $('li');
$all_lis.on('click', function() {
var index = $all_lis.index(this);
alert(index);
});
第一个项目为0
,最后一个项目为8
(即第9个项目).
The first item will give 0
, the last item will give 8
(i.e. 9th item).
这篇关于使用jQuery识别在多级列表中单击了哪个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!