parent vs closest

后端 未结 7 1265
终归单人心
终归单人心 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 19:20

    Because parent() will return the parent (immediate ancestor) only if it matches the selector specified.

    However, closest() will search all ancestors and return the first one that matches the selector.

    As the parent of button_30 is a div, whose parent is the div with the class of portlet, the parent() function is not matching it and returning an empty set, where-as closest() is matching it.


    To complete the set of similar methods here you have parents(), which is like closest() but doesnt stop at the first matched element; it returns all ancestors which match the selector.

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