父母与最近

osh*_*nen 21 html jquery jquery-selectors

为什么这样做:

$('.button_30').click(function(){
    $(this).closest('.portlet').find('.portlet_content').text("foo");
});?
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用:

$('.button_30').click(function(){
    $(this).parent('.portlet').find('.portlet_content').text("foo");
});?
Run Code Online (Sandbox Code Playgroud)

其中html看起来像这样:

<div class="portlet portlet_30">

    <div class="portlet_header portlet_header_30">
        header content here
    </div>

    <div class="portlet_sub_header portlet_sub_header_30">
        <input type="text" class="textbox_30" />
    </div>

    <div class="portlet_content portlet_content_30">
        results go here
    </div>

    <div class="portlet_footer portlet_footer_30">
        <input type="button" class="button_30" />
    </div>

</div>

<div class="portlet portlet_30">

    <div class="portlet_header portlet_header_30">
        header content here
    </div>

    <div class="portlet_sub_header portlet_sub_header_30">
        <input type="text" class="textbox_30 />
    </div>

    <div class="portlet_content portlet_content_30">
        results go here
    </div>

    <div class="portlet_footer portlet_footer_30">
        <input type="button" class="button_30" />
    </div>

</div>
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 37

因为只有匹配指定的选择器parent()才会返回父(直接祖先).

但是,closest()将搜索所有祖先并返回与选择器匹配的一个祖先.

作为父button_30div,其父是div与类的portlet,该parent()函数不匹配,并返回一个空集,其中,作为closest() 匹配它.


要完成一系列类似的方法,在这里你有parents(),这就好比closest()犯规停在第一个匹配元素; 它返回与选择器匹配的所有祖先.


cli*_*ity 35

  • .parent() 只关注直系祖先.

  • .closest() 查看所有祖先以及原始元素,并返回第一个匹配项.

  • .parents() 查看所有祖先,并返回所有匹配项.

  • 最近和父母之间有趣的表现比较:http://jsperf.com/jquery-parents-vs-closest/45 (2认同)