javascript 具有包含值的属性的 jQuery 最近元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12877943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:19:22  来源:igfitidea点击:

jQuery closest element with an attribute that contains a value

javascriptjquery

提问by Scott

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". 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". Is this possible? If so, how would I go about it?

在其中一行中,我想向上遍历 DOM 以找到最近的元素,该元素的 ID 属性以“nbContent_GR”开头。所以基本上我希望能够在不知道其确切 ID 的情况下找到父 TR 元素,只是第一个以“nbContent_GR”开头的元素。这可能吗?如果是这样,我将如何处理?

BTW, I'm aware of the closest() and "contains" selectors, just not sure if contains can be used on attribute values or not.

顺便说一句,我知道最接近的()和“包含”选择器,只是不确定包含是否可以用于属性值。

回答by Nelson

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”开头的父级

回答by RASG

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

回答by sync

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. Then use the 'starts with' selector to find an ID which starts with your required value.

从 TR 内,找到最近的 TR。然后使用“开头为”选择器查找以您所需值开头的 ID。

E.g.:

例如:

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