考虑下面的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);
}
};
我知道parent(expr)方法,但我看到的是允许你过滤一级的父级,直到找到expr才爬树(我喜欢代码示例证明我错了)