考虑以下 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/less-verbose
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);
}
};
我知道 parent(expr) 方法,但从我所看到的情况来看,它允许您向上过滤父母并且在找到 expr 之前不要爬树(我希望代码示例证明我错了)