是否有jQuery选择器/方法来查找特定的父元素?

时间:2022-11-28 09:22:26

Consider the following HTML. If I have a JSON reference to the <button> element, how can I get a reference to the outer <tr> element in both cases

考虑下面的HTML。如果我对

<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>

I know I could special case each condition, but I'm more interested "however deep you happen to be, climb the tree until you find element X" style solution. Something like this, but more jQuery like/less-verbose

我知道我可以在每个条件下都有特殊情况,但我更感兴趣的是“不管你有多深,爬到树上去,直到找到元素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);
    }
};  

I know about the parent(expr) method, but from what I've seen is allows you filter parents one level up and NOT climb the tree until you find expr (I'd love code example proving me wrong)

我知道父(expr)方法,但从我所看到的是,允许您过滤父母一层,而不是爬树,直到您找到expr(我喜欢代码示例来证明我是错误的)

3 个解决方案

#1


89  

The parents function does what you want:

父母的功能是你想要的:

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

#2


41  

Also, if you are using jQuery 1.3+ you can use the closest method

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

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

#3


0  

not jQuery but this options works much better

不是jQuery,但是这个选项更好。

node.contains( otherNode )

节点。包含(otherNode)

The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not

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

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

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

#1


89  

The parents function does what you want:

父母的功能是你想要的:

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

#2


41  

Also, if you are using jQuery 1.3+ you can use the closest method

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

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

#3


0  

not jQuery but this options works much better

不是jQuery,但是这个选项更好。

node.contains( otherNode )

节点。包含(otherNode)

The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not

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

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

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