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

Ala*_*orm 51 javascript jquery dom jquery-selectors

请考虑以下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>
Run Code Online (Sandbox Code Playgroud)

我知道每种条件我都可以处于特殊情况,但我更感兴趣的是"无论你遇到多么深刻,爬上树直到你找到元素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);
    }
};  
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*Seb 98

父母的功能你想要做什么:

$(this).parents("tr:first");
Run Code Online (Sandbox Code Playgroud)

  • 希望你不介意,我添加了文档的链接. (8认同)
  • 当然,谢谢!这就是"编辑其他人的帖子"权限;) (3认同)

ben*_*wey 44

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

$(this).closest("tr");
Run Code Online (Sandbox Code Playgroud)

  • 只是想补充一点,"最接近"和"父母"非常相似,但略有不同.您可以阅读更多[此处](http://api.jquery.com/closest/#entry-longdesc).总的来说,我认为"最接近"的方法对于这种特定情况更有效. (4认同)