22

为什么会这样:

$('.button_30').click(function(){
    $(this).closest('.portlet').find('.portlet_content').text("foo");
});​

为什么这不起作用:

$('.button_30').click(function(){
    $(this).parent('.portlet').find('.portlet_content').text("foo");
});​

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>
4

7 回答 7

38

因为当它与指定的选择器匹配时parent()才会返回父级(直接祖先) 。

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

由于父级button_30是 a div,其父级是div具有 类的portlet,因此该parent()函数不匹配它并返回一个空集,其中closest() -as匹配它。


要在这里完成一组类似的方法,你有parents(),这就像closest()不会在第一个匹配的元素处停止;它返回与选择器匹配的所有祖先。

于 2012-05-08T13:21:33.307 回答
35
  • .parent()只看直系祖先。

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

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

于 2012-05-08T13:21:38.880 回答
1

parent()只能向上看一级,可以尝试parents()一直向上搜索

$('.button_30').click(function(){
    $(this).parents('.portlet').find('.portlet_content').text("foo");
});​

你可以看到文档

于 2012-05-08T13:21:53.903 回答
1

[ closestAPI Ref]方法向上遍历祖先树,直到找到匹配的选择器。

[ parentAPI Ref]方法只查看直接父级。

于 2012-05-08T13:22:15.353 回答
1

parent方法仅检查元素链的上一级,同时closest将继续检查父级列表,直到找到匹配项(或到达 html 标记)。等效的是:

$('.button_30').click(function(){
    $(this).parents('.portlet:eq(0)').find('.portlet_content').text("foo");
});​
于 2012-05-08T13:22:30.783 回答
0

因为唯一匹配的元素.portlet祖父母,而不是绑定事件的元素的父母

于 2012-05-08T13:22:06.617 回答
0

因为在第二个选择器中,您正在寻找父节点,并且此函数移动到 DOM节点父亲,但仅one level包含类portlet_footer portlet_footer_30而不是您传递给选择器.portlet以使用的类,parent换句话说,您应该移动两个级别.

each time that you're using parent you move one node up

于 2012-05-08T13:23:29.970 回答