如何选择与选择器匹配的第一个祖先? [英] How To Select First Ancestor That Matches A Selector?

查看:115
本文介绍了如何选择与选择器匹配的第一个祖先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常规:

如何在jQuery中选择元素的第一个匹配祖先?

How can I select the first matching ancestor of an element in jQuery?

示例:

采用此HTML块

<table>
    <tbody>
        <tr>
            <td>
                <a href="#" class="remove">Remove</a>
            </td>
        </tr>
        <tr>
            <td>
                <a href="#" class="remove">Remove</a>
            </td>
        </tr>
    </tbody>
</table>

我可以通过使用以下jQuery代码单击删除"来删除表中的行:

I can remove a row in the table by clicking "Remove" using this jQuery code:

$('.remove').click(function(){
    $(this).parent().parent().hide();
    return false;
});

这有效,但是非常脆弱.例如,如果有人将<a>放入<div>中,它将损坏. jQuery中是否有遵循以下逻辑的选择器语法:

This works, but it's pretty fragile. If someone puts the <a> into a <div>, for example, it would break. Is there a selector syntax in jQuery that follows this logic:

这是一个元素,现在找到与某些选择条件匹配的最接近的祖先,然后将其返回"

"Here's an element, now find the closest ancestor that matches some selection criteria and return it"

谢谢

推荐答案

那将是 closest :

$(this).closest('tr').hide();

这篇关于如何选择与选择器匹配的第一个祖先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆