59

考虑以下 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 之前不要爬树(我希望代码示例证明我错了)

4

3 回答 3

108

父母功能做你想做的事:

$(this).parents("tr:first");
于 2009-03-30T21:10:11.620 回答
49

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

$(this).closest("tr");
于 2009-03-30T21:15:55.977 回答
0

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

node.contains( otherNode )

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

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

于 2017-01-31T12:53:50.553 回答