简体   繁体   English

jQuery最接近的元素,其属性包含一个值

[英]jQuery closest element with an attribute that contains a value

I have some HTML code that looks like this: 我有一些看起来像这样的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>

Within one of the rows, I want to traverse up the DOM to find the closest element that has an ID attribute that starts with "nbContent_GR". 在其中一行中,我想遍历DOM以查找具有以“ nbContent_GR”开头的ID属性的最近的元素。 So basically I want to be able to find the parent TR element without knowing its exact ID, just the first one that starts with "nbContent_GR". 因此,基本上我希望能够在不知道其确切ID的情况下找到父TR元素,只是第一个以“ nbContent_GR”开头的元素。 Is this possible? 这可能吗? If so, how would I go about it? 如果是这样,我将如何处理?

BTW, I'm aware of the closest() and "contains" selectors, just not sure if contains can be used on attribute values or not. 顺便说一句,我知道最近的选择器和“包含”选择器,只是不确定是否可以在属性值上使用包含。

Just do: 做就是了:

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

that will traverse the DOM up until it finds a parent with ID starting with 'nbContent_GR' 它将遍历DOM,直到找到ID以'nbContent_GR'开头的父级为止

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

Two useful pages to look at: 有两个有用的页面可供查看:

http://api.jquery.com/closest/ http://api.jquery.com/closest/

http://api.jquery.com/attribute-starts-with-selector/ http://api.jquery.com/attribute-starts-with-selector/

I think you can combine these for a solution. 我认为您可以结合使用这些解决方案。

From within the TR, find the closest TR. 在TR中,找到最接近的TR。 Then use the 'starts with' selector to find an ID which starts with your required value. 然后使用“开始于”选择器来查找以所需值开头的ID。

Eg: 例如:

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

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

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