2012-05-08 41 views
20

为什么这个工作:父VS最接近

$('.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'是父。 –

+0

它与家长在这里进行比较:https://api.jquery.com/closest/ –

回答

38

因为parent()会返回父母(直系祖先)只有如果它匹配sele ctor指定。

然而,closest()将搜索所有祖先和返回的选择相匹配的第一之一。

作为button_30母体是div,其父为div与类的portlet,所述parent()函数不匹配,并返回一个空集,其中,作为closest()匹配它。


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

33
  • .parent()只看直接的祖先。

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

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

+1

最近和父母在这里有趣的表现比较:http://jsperf.com/jquery-parents-vs-closest/45 –

1

parent()只关注一个级别,你可以尝试parents()搜索所有一路

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

可以看到documentation

0

由于匹配其唯一的元素.portlet祖父母 ,而不是事件所绑定元素的父母

1

parent方法只检查元素链上的一个级别,而closest将继续检查父级列表直到找到匹配(或已达到html标记)。 相对应的是:

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

因为在第二个选择,你要寻找的父母和这个功能移动的进入DOM到节点的父亲,但只有one level其中包含你的类portlet_footer portlet_footer_30不是类传递给选择器.portletparent一起工作,换句话说,你应该移动两个层次。

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