[英]jquery find all elements with class and return the count position of the clicked Element
I am not looking for $(this).index()
as an FYI.我不是在寻找
$(this).index()
作为仅供参考。 So, what I have are two <ul>
tags with <li>
tags within them.所以,我有两个
<ul>
标签,里面有<li>
标签。 I want to know which <ul>
was clicked and which <li>
was clicked.我想知道单击了哪个
<ul>
以及单击了哪个<li>
。 For example something like ul 0 and li 3. So if there are 10 <ul>
tags on the page I only want to look at the ones with the list
class for clicks.例如像 ul 0 和 li 3 这样的东西。因此,如果页面上有 10 个
<ul>
标签,我只想查看带有list
class 的标签以进行点击。
jQuery Example that will not work for what I want: jQuery 示例不适用于我想要的:
$('ul').click(function(event) { alert($(this).index()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> <hr /> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul>
The wanted outcome of the clicked element: UL # and LI #.点击元素的期望结果:UL # 和 LI #。 Like UL0 LI3, UL1 LI3, etc...
像UL0 LI3, UL1 LI3, 等等...
JSFiddle: http://jsfiddle.net/cg3a8d6n/ JSFiddle: http://jsfiddle.net/cg3a8d6n/
You could use click event on li
element and then get its index and also the index of its parent which is ul
.您可以在
li
元素上使用 click 事件,然后获取其索引以及其父级的索引ul
。 You can also specify selector inside the index
method to consider only specific elements that match the selector.您还可以在
index
方法中指定选择器,以仅考虑与选择器匹配的特定元素。
$('ul.list li').click(function(event) { const li = $(this).index(); const ul = $(this).parent().index('ul.list'); console.log(`ul: ${ul} li: ${li}`) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> <hr /> <ul></ul> <ul></ul> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.