有没有一个jQuery的select器/方法来find一个特定的父级元素水平了?

考虑下面的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> 

我知道我可以特殊情况下的每一个条件,但我更感兴趣的是“无论你身在何处,爬到树上,直到find元素X”的风格解决scheme。 像这样的东西,但更多的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); } }; 

我知道父(expr)方法,但从我看到的是允许你过滤父母一级,而不是爬树,直到你findexpr(我喜欢代码示例certificate我错了)

父母的function是做你想做的:

 $(this).parents("tr:first"); 

另外,如果你使用的是jQuery 1.3+,你可以使用最接近的方法

 $(this).closest("tr"); 

不是jQuery,但这个选项效果更好

node.contains(otherNode)

Node.contains()方法返回一个布尔值,指示节点是否是给定节点的后代

https://developer.mozilla.org/en/docs/Web/API/Node/contains