简体   繁体   English

如何通过 class 获取点击元素的索引?

[英]How to get the index of clicked element by class?

I want to get the index of the clicked element in its list as well in its .blue class.我想在其列表中以及在其.blue class 中获取单击元素的索引。

I figured out how to get the index in its list, but I can't figure out how to get the index in its .blue class.我想出了如何在其列表中获取索引,但我不知道如何在其.blue class 中获取索引。 For example when I click the 5th button I want the to show 'index 4 - class index 3'.例如,当我单击第 5 个按钮时,我希望显示“索引 4 - class 索引 3”。

Any ideas?有任何想法吗?

 $('.showindex').click(function() { var index = $(this).closest("li").index(); console.log("index " + index + " - class index " + "?"); });
 .blue { color: blue; }
 <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <ol id="ol1"> <li><input type="button" value="Show index" class="showindex blue">showindex blue</li> <li><input type="button" value="Show index" class="showindex">showindex</li> <li><input type="button" value="Show index" class="showindex blue">showindex blue</li> <li><input type="button" value="Show index" class="showindex">showindex</li> <li><input type="button" value="Show index" class="showindex blue">showindex blue</li> </ol>

To achieve this you can select all .blue elements and provide the current element as an argument to find its index within that collection.为此,您可以 select 所有.blue元素并提供当前元素作为参数以在该集合中查找其索引。

Note that the last button will show its 'class index' as 2 because indexes are zero-based in JS.请注意,最后一个按钮将其“类索引”显示为2 ,因为索引在 JS 中是从零开始的。 Try this:尝试这个:

 let $blues = $('li:has(.showindex.blue)'); $('.showindex').click(function() { let $li = $(this).closest('li'); let index = $li.index(); let classIndex = $blues.index($li); console.log(`index ${index}, class index ${classIndex}`); });
 .blue { color: blue; }
 <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <ol id="ol1"> <li><input type="button" value="Show index" class="showindex blue">showindex blue</li> <li><input type="button" value="Show index" class="showindex">showindex</li> <li><input type="button" value="Show index" class="showindex blue">showindex blue</li> <li><input type="button" value="Show index" class="showindex">showindex</li> <li><input type="button" value="Show index" class="showindex blue">showindex blue/li> </ol>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM