开发者

Is this selector valid?

Is this selector valid? and what $(this) refer to?

$('div', $(this).p开发者_StackOverflow社区arents('div'))

i just learn javascript and jquery, thanks


It's valid. It's taking all of the parent divs of this and then finding all of the divs underneath them. Breaking it down:

var jq = $(this);                // Get a jQuery object for `this`
var parents = jq.parents('div'); // Find all of its parents that are divs
var divs = $('div', parents);    // Find all divs under those parent divs

The result is a jQuery object with matches for all of the divs that are descendants of the divs that are parents of this. More here and here.

Example: Let's assume that this initially refers to the input element foo below:

<div id='d1'>
    <div id='d2'>
        <input id='foo' type='button'>
        <div id='d3'>
        ...
        </div>
    </div>
    <div id='d4'>
        <div id='d5'>
        ...
        </div>
    </div>
</div>

$(this).parents('div') will match d1 and d2. Then $('div', parents) will match:

  • d3
  • d2 (beacuse in addition to being one of the parents, it's a child of d1)
  • d4
  • d5


Actually:

$('div', $(this).parents('div'))

The jQuery function (jquery() or $()) needs at least one parameter of selector and second optional one is for a context, in your example $(this).parents('div').

So, above code is going to perform on $(div) which is inside the context $(this).parents('div'). However, this is not that much usual, it most cases, it looks like:

$('#element').click(function(){
    $('div', this).addClass('some class');
});

In the above case, this refers to #element and then adds class to div inside that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜