If this() selector is used inside a function, which selector will it refer to (jQuery)?
For instance I have a function:
function somefunction () {
$('someselector').fadeOut('slow', f开发者_如何学编程unction() { $(this).remove; });
}
Then this function is called within:
$('someselector1').click(function() {
somefunction ();
});
Will the $(this)
inside somefunction()
refer to someselector()
or to someselector1()
? As I understand it, this()
refers to the selector that triggered the event, which is in this case, someselector1. Is it correct?
It will refer to a DOM element matching someselector
. this
is set to the element the fadeOut
function is being applied to.
this
inside of someFunction
(but not inside the callback function to fadeOut
) will be a reference to the window
object.
function somefunction () {
// "this", unless specifically set, will refer to "window"
$('someselector').fadeOut('slow', function() {
// "this" refers to the element that just finished fading out.
$(this).remove;
});
}
Example: http://jsfiddle.net/9ubgH/
Note that there's nothing magic about the $(this)
syntax -- it just takes whatever this
points to and feeds it to the (heavily overloaded) main jQuery entry point, and what jQuery does with depends entirely on what kind of thing it is. In particular, JQuery doesn't know that you got its argument from a this
.
This is relevant because just being in a function does not tell you anything about what this
will be -- that's up to the caller of the function, more or less, to decide. In your case the function happens to be called from code that sets this
to something predictable, but that is not something you can assume about functions in general.
It will refer to someselector
.
$('someselector').fadeOut('slow', function() { $(this).remove; });
In the above fadeOut
callback this
will point to the element which it is fading so this
will point to someselector
.
In this case this will refer to "someselector".
check this fiddle http://jsfiddle.net/6gdnw/
精彩评论