What does the 'this' word do in the following line of jQuery do?
What does the this
part of the following line of jQuery do?
$('span:visible:f开发者_StackOverflow中文版irst', this);
It restricts the search specified in the first argument to the context of the this
object.
Only children of this
that match the specified requirements will be selected. Without the context, the search will apply to the whole document.
From the docs:
jQuery( selector, [ context ] )
context A DOM Element, Document, or jQuery to use as context
Maybe turning it around would be the simplest explanation, it gets turned into this:
$(this).find('span:visible:first');
So it's using .find()
to get all descendants of this
(whatever that element is) that match your 'span:visible:first'
selector.
As the this
keyword is the current object, it depends on where that code is placed. If you specify a second parameter, it's used as context for the search, i.e. it will only look for elements within that context.
If you use that on it's own, this
is the same as window
so it's the same as $('span:visible:first', window)
.
If you use it inside an event handler, this
is the element that the event was triggered on, so it will only seach for matches within that element.
精彩评论