[英]Jquery selector via parents?
I have this simple table ( nested ) 我有这个简单的表(嵌套)
<table border="1px">
<tr>
<th>kkkk</th>
<th>mmmm</th>
</tr>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td>a</td>
<td>
<table border="1px" style="margin:10px">
<tr>
<th>xxxx</th>
<th style="background-color:yellow">yyyy</th>
</tr>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td >a</td>
<td style="background-color:red;" class="theTd">a</td>
</tr>
</table>
</td>
</tr>
</table>
(there aren't any table Id's here) (这里没有任何表格ID)
I want by clicking on the red
area , to find the row which the yellow
value in. 我想通过单击
red
区域,找到yellow
值所在的行 。
I dont have a problem of getting the index of the TH
. 我没有获取
TH
的索引的问题。
the problem is that I want to do it by Parents()
method only - and the red box sees 2 parents TR's
which have TH
.... The xxx,yyy row and the kkk,mmm row... 问题是我只想通过
Parents()
方法执行此操作-红框看到2个具有TH
...的parents TR's
TR。xxx,yyy行和kkk,mmm行...
Something like : 就像是 :
alert( $(".theTd").parents("first tr parent which contains th's").....);
What is the correct Selector syntax ? 正确的选择器语法是什么?
http://jsbin.com/udohum/1/edit http://jsbin.com/udohum/1/edit
I don't want the ordinary parent().parent().... cause a .theTd
can contain a wrapper Div's inside it etc... - so the parent here will be DIV. 我不希望普通的parent()。parent()....导致
.theTd
可以在其中包含包装Div等等,所以-这里的父母将是DIV。 ( which hurts the logic....) (这会损害逻辑。
What about something like this? 那这样的东西呢?
$('.theTd').click(function(){
alert($(this).parent().parent().find('tr > th:nth-child(2)').html());
});
(See it working here: http://jsfiddle.net/Te3QB/1/ ) (在这里查看它的工作原理: http : //jsfiddle.net/Te3QB/1/ )
UPDATE: Using the .closest()
selector might even be better: 更新:使用
.closest()
选择器可能会更好:
$('.theTd').click(function(){
alert($(this).closest('table').find('tr > th:nth-child(2)').html());
});
.closest()
gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree..closest()
获取与选择器匹配的第一个元素,从当前元素开始,一直扩展到DOM树。
parents()
selects all the parents of the selected element, you can use parentsUntil
instead: parents()
选择选定元素的所有父级,您可以改用parentsUntil
:
$(".theTd").parentsUntil('table').find('th[style^=background]')
Or closest()
method: 或
closest()
方法:
$(".theTd").closest('table').find('tr:has("th")').foo()
To get the tr, try this: 要获取tr,请尝试以下操作:
$(".theTd").closest("table").find("tr");
The th is a bit more messy. 这个有点杂乱。 We will need the nth-child, and for that we need the index:
我们将需要第n个孩子,为此,我们需要索引:
$(this).closest('table').find('tr th:nth-child('+ ($(this).index()+1) +')');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.