使用jQuery选择类的父元素

时间:2012-08-17 17:43:54

标签: javascript jquery

JS:

$(function(){
    $(".remove").click(function(){
        $("<need the right selector>").hide();
    });
});

HTML:

<div class="tag-collection">
    <div class="key">PULMONARY_EMBOLISM <span class="remove">✘</span></div>
</div>

我会删除上面的jQuery代码来删除整个div tag-collection。但是,我会在页面上有很多tag-collection个div,我想确保当有人点击删除按钮时它只会删除包含删除按钮的tag-collection div。

4 个答案:

答案 0 :(得分:4)

如果你有很多,这将绑定更少的听众,所以它更“有效”/更轻量级:

$(function(){
    $(document).on('click', 'span.remove', function() {
        $(this).closest('.tag-collection').hide();
    });
});

答案 1 :(得分:1)

$(".remove").click(function(){
    $(this)  // points to clicked element
        .closest('.tag-collection') // jump to parent tag-collection
        .hide(); // hide that
});

答案 2 :(得分:1)

$(function(){
    $(".remove").click(function(){
        $(this).parents('.tag-collection').hide();
    });
});

强调第3行。

修改:正如Kevin B所述,将parents()替换为closest()可能更好,因为这只会选择一个祖先。< / p>

答案 3 :(得分:1)

您可以使用closest方法,试试这个:

$(function(){
    $(".remove").click(function(){
        $(this).closest('.tag-collection').remove();
    });
});
相关问题