有没有办法选择这个家长?

时间:2013-03-14 05:11:13

标签: jquery html

<div class="chatbox-window">
    <div class="chatbox-title">
        <div class="chatbox-username"></div><div class="chatbox-close"><span class="chatbox-close-button"></span></div>
    </div>
    <div class="chatbox-content"><div class="chatbox-msg"></div></div>
    <div id="chatbox-posting"></div>
</div>

    $(".chatbox-close-button").click(function(){
        $(this).parent(".chatbox-close").parent(".chatbox-title").parent(".chatbox-window").remove();
    });

下面,我使用:

$(this).parent(".chatbox-close").parent(".chatbox-title").parent(".chatbox-window") to get the ".chatbox-window"

可是:

是否有更短的方法来获取.chatbox-window

聚苯乙烯。如果不更改HTML代码。

4 个答案:

答案 0 :(得分:1)

使用parents()

Official Document

描述:获取当前匹配元素集中每个元素的祖先,可选择通过选择器进行过滤。

$(this).parents(".chatbox-window").remove();

答案 1 :(得分:0)

使用.closest()

  

对于集合中的每个元素,获取与之匹配的第一个元素   选择器通过测试元素本身并遍历其中   DOM树中的祖先。

$('.chatbox-close-button').click(function(){
    $(this).closest('.chatbox-window').remove();
});

演示:Fiddel

答案 2 :(得分:0)

 $(this).parents('div:eq(0)').remove();

答案 3 :(得分:0)

您可以使用jquery nearest()。文档here

$(this).closest('.chatbox-window').remove()