【问题标题】:parent vs closest父母与最亲近的人
【发布时间】:2012-05-16 23:38:46
【问题描述】:

为什么会这样:

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

【问题讨论】:

  • 因为.portlet不是.button_30的父级,所以.portlet_footer是父级。
  • 这里是和父母比较的:api.jquery.com/closest

标签: jquery html jquery-selectors


【解决方案1】:

因为parent() 将返回父(直系祖先)只有如果它匹配指定的选择器。

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

由于button_30 的父级是div,其父级是div,类为portletparent() 函数不匹配它并返回一个空集,其中@ 987654331@ 匹配它。


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

【讨论】:

    【解决方案2】:
    • .parent() 只查看直接祖先。

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

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

    【讨论】:

    【解决方案3】:

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

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

    你可以看到documentation

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

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

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

          【讨论】:

            【解决方案7】:

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

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-07-09
              • 1970-01-01
              相关资源
              最近更新 更多