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:
d3d2(beacuse in addition to being one of the parents, it's a child ofd1)d4d5
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.
加载中,请稍侯......
精彩评论