jQuery - 按子类选择父类?
问题描述:
如何选择含有孩子<div class="test">
的<tr>
,如下?jQuery - 按子类选择父类?
<table>
<tr> <!-- this tr is what I want to select -->
<td>
<div class="test"> text </div>
</td>
</tr>
</table>
答
$("div.test").parents("tr");
// Or
$("div.test").closest("tr");
(最初的选择可以是任何东西,你的div
相匹配,所以".test"
将被罚款了。)
parents
看起来一路上涨的树,可能匹配多个tr
元素,如果你有一个表内的表。 closest
将停止,并遇到div
的每个tr
。
下面是一个使用closest
一个例子:
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:
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);
}
});
输出:
Matched 3 rows: Row 'first' Row 'second' Row 'third'
答
$('.test').parent('tr')
这种选择正是你想要的。
答
$('.test').parent().parent();
或$('.text').parent().closest('tr');
答
的下面内的儿童和在某处类的。测试目标的父以下示例将背景更改为红色...
$(document).ready(function(){
$('.test').parents('tr').css('background-color', 'red');
});
对我努力的目标从InDesign导出HTML时,这是非常强大的。强大,因为indesign不会让你标记,但通过这个你可以标记一个,然后通过这个JQuery。