If I have the following JQuery:
$('#div1, #div2').scroll(function() { my_function($(this)); });
or
$('#div1, #div2').live('mouseover',function(){ my_function($(this)); });
What does $(this)
represent?
Is it the DOM object of either DIV1 or DIV2? Or is it the HTML of that DIV?
What does "this" represent in the code above?
If I have the following JQuery:
$('#div1, #div2').scroll(function() { my_function($(this)); });
or
$('#div1, #div2').live('mouseover',function(){ my_function($(this)); });
What does $(this)
represent?
Is it the DOM object of either DIV1 or DIV2? Or is it the HTML of that DIV?
What does "this" represent in the code above?
Share Improve this question asked Nov 9, 2010 at 20:50 StaceyHStaceyH 7392 gold badges7 silver badges7 bronze badges4 Answers
Reset to default 8this
is the DOM element on which the event was fired, in this case #div1
or #div2
.
$(this)
is a call to jQuery to wrap the DOM element in jQuery's wrapper, so you can use jQuery functions (e.g. .text()
, .bind()
, .load()
) on it.
this
represents the DOM element that fired the event, either #div1
or #div2
.
this
will be the DOM element on which the event was fired (#div1
if you mouseover #div1
, ...)
Check out this section of the jQuery documentation:
http://api.jquery./jQuery/#using-dom-elements
In the context of any jQuery callback function, this
is set to the DOM element being operated on by the function. In your case, the callback function is operating on the one of the two DOM elements specified by your selector, either #div1
or #div2
.
As lonesomeday noted, in order to use jQuery operations on the element, you need to wrap it in the jQuery object. That is what $(this)
is. It simply says "take this DOM element and give it to me in a jQuery object."
Be aware: a mon gotcha when using this
is changed context. For example, if you were to do this:
$(function() {
$('#div1').click(function() {
var myThis1 = this;
$('.divs').each(function() {
var myThis2 = this;
});
});
});
myThis1
would be the DOM object for #div1
, but inside your .each()
call, the context of this
changes. myThis2
would, on each loop through, be set to a DOM object for the some element with the divs
class. Just something to look out for :)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744156730a4560896.html
评论列表(0条)