如何在 jquery 中获取 $(this) 的特定上限 class

How to get a specific upper class of $(this) in jquery

我有以下 html.

<div class="new-row>
   <img class="trash" src = "trash.png">
   <img class="trash" src = "trash.png">
</div>
<div class="new-row>
    <img class="trash" src = "trash.png">
    <img class="trash" src = "trash.png">
</div>

我还有以下 jquery 代码

$(".trash").on("click",trashClicked);

如何在每个新行中获取(“.trash”)的数量class。我不想获得带有 class 个垃圾的 img 标签的总数。当在特定的新行

中单击垃圾图像时,我想获得带有 class 垃圾的特定数量的 img 标签

trashClicked 中,this 将引用被单击的特定 img。然后,您可以从那里计算出该行中有多少 .trash img

  1. 您的 img 元素是彼此的兄弟姐妹,因此您可以使用 siblings:

    var count = $(this).siblings().length + 1; // + 1 for the one we're calling it on
    
  2. 更通用的解决方案是使用 closest to find the enclosing .new-row, and then find 查找所有 .trash 元素,即使它们处于不同级别。

    var count = $(this).closest(".new-row").find(".trash).length;
    

非常值得 您花时间从头到尾通读 jQuery API。它不会花很长时间,而且它几乎会立即回报你花在这件事上的时间。