parent vs closest

后端 未结 7 1266
终归单人心
终归单人心 2021-01-07 18:33

Why does this work:

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

an

相关标签:
7条回答
  • 2021-01-07 18:57

    parent() only looks one level up, you can try parents() to search all way up

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

    you can see the documentation

    0 讨论(0)
  • 2021-01-07 19:02

    The parent method checks only one level up the chain of elements, while closest will keep checking the list of parents up until a match is found (or html tag has been reached). The equivalent is:

    $('.button_30').click(function(){
        $(this).parents('.portlet:eq(0)').find('.portlet_content').text("foo");
    });​
    
    0 讨论(0)
  • 2021-01-07 19:05

    Because in the second selector you're looking for the Parent and this function move's into the DOM to the node father but only one level which contains the class portlet_footer portlet_footer_30 not the classes that you're passing to the selector .portlet to work with parent you should move two levels in other words.

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

    0 讨论(0)
  • 2021-01-07 19:09

    The closest[API Ref] method traverses up the ancestor tree as far as it needs to go to find a selector match.

    The parent[API Ref] method only looks at the direct parent.

    0 讨论(0)
  • 2021-01-07 19:10

    Because the only elements which match .portlet are grandparents, not parents of the elements on which the event is bound

    0 讨论(0)
  • 2021-01-07 19:12
    • .parent() only looks at the immediate ancestor.

    • .closest() looks at all ancestors, as well as the originating element, and returns the first match.

    • .parents() looks at all ancestors, and returns all matches.

    0 讨论(0)
提交回复
热议问题