[英]Is there a jQuery selector/method to find a specific parent element n levels up?
請考慮以下HTML。 如果我有一個對<button>元素的JSON引用,如何在兩種情況下獲得對外部<tr>元素的引用
<table id="my-table">
<tr>
<td>
<button>Foo</button>
</td>
<td>
<div>
<button>Bar</button>
</div>
</td>
</tr>
</table>
<script type="text/js">
$('#table button').click(function(){
//$(this).parent().parent() will work for the first row
//$(this).parent().parent().parent() will work for the second row
//is there a selector or some magic json one liner that will climb
//the DOM tree until it hits a TR, or do I have to code this myself
//each time?
//$(this).????
});
</script>
我知道每種條件我都可以處於特殊情況,但我更感興趣的是“無論你遇到多么深刻,爬上樹直到你找到元素X”的風格解決方案。 像這樣的東西,但更多jQuery喜歡/更少詳細
var climb = function(node, str_rule){
if($(node).is(str_rule)){
return node;
}
else if($(node).is('body')){
return false;
}
else{
return climb(node.parentNode, str_rule);
}
};
我知道父(expr)方法,但從我所看到的是允許你過濾父級一級,而不是爬樹直到你找到expr(我喜歡代碼示例證明我錯了)
父母功能做你想要的:
$(this).parents("tr:first");
此外,如果您使用的是jQuery 1.3+,則可以使用最接近的方法
$(this).closest("tr");
不是jQuery,但這個選項效果更好
node.contains(otherNode)
Node.contains()方法返回一個布爾值,指示節點是否是給定節點的后代
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.