jQuery选择最近具有包含特定值属性的元素

9

我有一些HTML代码看起来像这样:

<tr id="nbContent_GR1">...</tr>
<tr id="nbContent_GR2">...</tr>
<tr id="nbContent_GR3">...</tr>
<tr id="nbContent_GR4">...</tr>
<tr id="nbContent_GR5">...</tr>
<tr id="nbContent_GR6">...</tr>

在其中一行中,我想向上遍历DOM树以查找最接近的具有ID属性以"nbContent_GR"开头的元素。因此,基本上我想能够找到父TR元素而不知道它的确切ID,只需找到以"nbContent_GR"开头的第一个元素。这种情况可能吗?如果可以,我该如何实现?

顺便说一下,我知道closest()和"contains"选择器,只是不确定是否可以在属性值上使用contains。


抱歉,我不明白你所问的问题。 - The Alpha
4个回答

15

只需执行以下操作:

tr = $(this).closest("[id^='nbContent_GR']");

这将遍历DOM,直到找到一个ID以'nbContent_GR'开头的父元素。


完美,我知道我错过了一个简单的解决方案。 :) 我不知道“^”的用途。一定要喜欢学习新东西。 - Scott

3
.closest('[id^="nbContent_GR"]')

2

0
这可能有点晚了,但对于像我一样想要以不同方式实现的人,我找到了这种方法。

$(document).on('click', '.btn-info', function() {
  var cardId = $(this).closest(".cardClass").attr("id");
  alert(cardId);
  console.log(cardId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div id="card1" class="cardClass">
    <button type="button" class="btn btn-info"></button>
  </div>
  <div id="card2" class="cardClass">
    <button type="button" class="btn btn-info"></button>
  </div>
  <div id="card3" class="cardClass">
    <button type="button" class="btn btn-info"></button>
  </div>
  <div id="cardn" class="cardClass">
    <button type="button" class="btn btn-info"></button>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接