开发者

JQuery: Help with ".live" and ".scroll"

If I have the following JQuery:

$('#div1, #div2').scroll(function() { my_function($(this)); });

or

$('#div1, #div开发者_JS百科2').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?


this 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.com/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 common 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 :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜