jquery child selector without parent

前端 未结 3 1896
旧巷少年郎
旧巷少年郎 2021-02-14 05:38

I was looking at some code from a tutorial for creating a carousel menu and noticed parent child selectors without the parent. Never seen this before, and confused to what it is

相关标签:
3条回答
  • 2021-02-14 06:12

    There is a parent(or in this case a scope), notice the this keyword inside the selector, that's relative to the element the plugin is being applied to.

    jQuery's selectors allow you to set a scope, and it can be any jQuery element object.

    Consider

    $(".somediv").myplugin();
    

    And inside the plugin

    $("> div", this) 
    is actually translated to 
    $("> div", $(".somediv"))
    

    Have a look at one of my questions, the answer explains quite a bit about jQuery's selectors. What is the fastest method for selecting descendant elements in jQuery?

    0 讨论(0)
  • 2021-02-14 06:17
    $('> div', this)
    

    The this is important. It's a context parameter that makes the query equal to

    $(this).children('div');
    

    See the documentation for $() for more information; it specifically mentions this:

    Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

    $(this).find('> div') means "the divs that are children of this, which is equal to $(this).children('div').

    0 讨论(0)
  • 2021-02-14 06:19

    This selector with a context:

    $('> div', this)
    

    gets flipped around to use a .find() like this:

    $(this).find('> div')
    

    which with the > child-selector is just:

    $(this).children('div')
    

    The others are doing the same deal, they could use .children(), and actually it'd be more efficient to do so.

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