父级元素 vs 最近的元素

23

为什么这个能够工作:

$('.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>

2
因为.portlet不是.button_30的父元素,所以.portlet_footer是其父元素。 - Felix Kling
这里与父元素进行比较:https://api.jquery.com/closest/ - Christophe Roussy
7个回答

38

parent() 只返回与指定选择器匹配的父级(直接祖先)

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

由于 button_30 的父级是一个具有portlet类的 div, 其父级是具有portlet类的另一个 div,因此 parent() 函数不匹配它并返回一个空集合,而 closest() 匹配到了该元素。


要完整一组类似方法,这里还有parents(),它类似于closest(),但不会止于第一个匹配的元素; 它将返回所有与选择器匹配的祖先元素。


36
  • .parent()仅查找直接的祖先元素。

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

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


2
这里有一个有趣的性能比较,涉及到closest和parents方法:http://jsperf.com/jquery-parents-vs-closest/45 - Zé Carlos

1

closest[API Ref]方法会遍历祖先树,直到找到选择器匹配为止。

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


1

parent() 只会向上查找一级,您可以尝试使用 parents() 查找所有的父级元素

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

你可以查看文档


1

parent方法只检查元素链中的一个级别,而closest会一直检查父元素列表,直到找到匹配项(或已到达html标记)。

等效的代码如下:

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

0

因为与.portlet匹配的唯一元素是事件绑定元素的父级的祖先元素,而不是其父级元素。


0

因为在第二个选择器中,您正在查找父级,并且此函数将进入 DOM 到节点父级,但仅限于包含类 portlet_footer portlet_footer_30一个级别,而不是您传递给选择器 .portlet 的类来使用 parent,您应该向上移动两个级别。

每次使用 parent 时,您都会向上移动一个节点


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接