jQuery最近元素的属性包含值

ulmd4ohb  于 2023-02-08  发布在  jQuery
关注(0)|答案(4)|浏览(172)

我有一些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是否可以用于属性值。

enyaitl3

enyaitl31#

只需:

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

它将遍历DOM,直到找到ID以"nbContent_GR"开头的父对象

zsbz8rwp

zsbz8rwp2#

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

kokeuurv3#

两个有用的页面看:
http://api.jquery.com/closest/
http://api.jquery.com/attribute-starts-with-selector/
我想你可以把这些结合起来作为一个解决方案。
从TR中查找最近的TR。然后使用"开头为"选择器查找以所需值开头的ID。
例如:

$(this).closest("tr").parent().find("id^='nbContent_GR'");
46scxncf

46scxncf4#

这可能是晚了,但对于那些喜欢我想要它有点不同的方式,我想出了这样的方式

<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>

$(document).on('click', '.btn-info', function () {
    var cardId = $(this).closest(".cardClass").attr("id");
    alert(cardId);
    console.log(cardId);
});

相关问题