简体   繁体   English

正确获取元素的索引

[英]Get index of element properly

For each .furcLeft I want to have its unique index, starting from number 1. With the provided code the first .furcLeft has number 1, but the second .furcLeft has number 3, and the next .furcLeft restarts from 1. This is not supposed to happen, the index should continue but not restart.对于每个.furcLeft ,我想拥有其唯一索引,从数字 1 开始。使用提供的代码,第一个.furcLeft的数字为 1,但第二个.furcLeft的数字为 3,下一个.furcLeft从 1 重新开始。这不是应该发生,索引应该继续但不重新启动。

 $(".furkation.bottom-addFurcation.furcLeft").each(function() { $(this).html(($(this).index()+1)); });
 <tr class="furkation"> <td class="bottom-addFurcation"> <div class="furcLeft"> <:-- Number 1 should appear here --> <div class="insert_furcation"></div> </div> <div class="divider"></div> <div class="furcLeft"> <.-- 2 --> <div class="insert_furcation"></div> </div> </td> <td class="bottom-addFurcation"> <div class="furcLeft"> <.-- 3 --> <div class="insert_furcation"></div> </div> <div class="divider"></div> <div class="furcLeft"> <.-- 4 --> <div class="insert_furcation"></div> </div> </td> <tr> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Try this:尝试这个:

 $(document).ready(function(){ $.each($(".furcLeft"), function(index, item) { $(item).html(index+1); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <tr class="furkation"> <td class="bottom-addFurcation"> <div class="furcLeft"> <!-- Number 1 should appear here --> <div class="insert_furcation"></div> </div> <div class="divider"></div> <div class="furcLeft"> <!-- 2 --> <div class="insert_furcation"></div> </div> </td> <td class="bottom-addFurcation"> <div class="furcLeft"> <!-- 3 --> <div class="insert_furcation"></div> </div> <div class="divider"></div> <div class="furcLeft"> <!-- 4 --> <div class="insert_furcation"></div> </div> </td> <tr>

Consider the following.考虑以下。

 $(".furkation.furcLeft").each(function(i, el) { $(el).html(i + 1); });
 <table> <tr class="furkation"> <td class="bottom-addFurcation"> <div class="furcLeft"> <:-- Number 1 should appear here --> <div class="insert_furcation"></div> </div> <div class="divider"></div> <div class="furcLeft"> <.-- 2 --> <div class="insert_furcation"></div> </div> </td> <td class="bottom-addFurcation"> <div class="furcLeft"> <.-- 3 --> <div class="insert_furcation"></div> </div> <div class="divider"></div> <div class="furcLeft"> <.-- 4 --> <div class="insert_furcation"></div> </div> </td> <tr> </table> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

When using .each() , it is passed an Index and an Element.当使用.each()时,它被传递一个索引和一个元素。 You can use this to label them if you choose.如果您选择,您可以将其用于 label 它们。

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

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