jQuery - 按子类选择父类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9557005/
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
jQuery - select parent by child class?
提问by Moamen
How can I select the <tr>
containing the child <div class="test">
, as below?
如何选择<tr>
包含 child <div class="test">
,如下所示?
<table>
<tr> <!-- this tr is what I want to select -->
<td>
<div class="test"> text </div>
</td>
</tr>
</table>
回答by T.J. Crowder
You can use parents
or closest
for that, depending on your needs:
您可以使用parents
或closest
为此,根据您的需要:
$("div.test").parents("tr");
// Or
$("div.test").closest("tr");
(The initial selector can be anything that matches your div
, so ".test"
would be fine too.)
(初始选择器可以是与您匹配的任何东西div
,所以".test"
也可以。)
parents
will look all the way up the tree, possibly matching multiple tr
elements if you have a table within a table. closest
will stop with the first tr
it encounters for each of the div
s.
parents
将一直向上查找树,tr
如果表中有表,则可能匹配多个元素。closest
将tr
在每个div
s遇到的第一个停止。
Here's an example using closest
:
这是一个使用示例closest
:
HTML:
HTML:
<table>
<tr id="first"> <!-- this tr I want to select -->
<td>
<div class="test"> text </div>
</td>
</tr>
<tr id="second"> <!-- this tr I want to select -->
<td>
<div class="test"> text </div>
</td>
</tr>
<tr id="third"> <!-- this tr I want to select -->
<td>
<div class="test"> text </div>
</td>
</tr>
</table>
JavaScript:
JavaScript:
jQuery(function($) {
var rows = $("div.test").closest("tr");
display("Matched " + rows.length + " rows:");
rows.each(function() {
display("Row '" + this.id + "'");
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Output:
输出:
Matched 3 rows: Row 'first' Row 'second' Row 'third'
回答by Iakovos Exadaktylos
Use selector :has() like:
使用选择器 :has() 像:
$("tr:has(div.test)");
Find jQuery documentation here :has() Selector
在此处查找 jQuery 文档:has() 选择器
回答by Frederick Behrends
$('.test').parent('tr')
this selects exactly what you want.
这正是您想要的选择。
回答by sinanakyazici
you should use
你应该使用
$('.test').parents('tr');
For Example:
例如:
回答by user2390741
The below targets the parent with class of .test somewhere within its children and in the below example changes background to red...
下面的目标是在其子级中某处具有 .test 类的父级,在下面的示例中将背景更改为红色...
$(document).ready(function(){
$('.test').parents('tr').css('background-color', 'red');
});
For me this is extremely powerful when trying to target exported html from indesign. Powerful because indesign does not let you tag 's but through this you can tag a and then the through this JQuery.
对我来说,这在尝试从 indesign 定位导出的 html 时非常强大。强大是因为 indesign 不允许你标记 's 但通过这个你可以标记 a 然后通过这个 JQuery。
回答by user1248376
$('.test').parent().parent();
or $('.text').parent().closest('tr');
$('.test').parent().parent();
或者 $('.text').parent().closest('tr');