开发者

What is the rule? when do i use $(this) and when is "this" enough?

I know that $(this) results in a jQuery object, but 开发者_如何学编程i often see (especieally in jQuery plugins) the use of return this.whatever what is the general rule?

Thanks


Use $(this) when you want to use JQuery functionality on 'this'.

Use 'this' when you don't want to use JQuery functionality on 'this'.


$(this) gives you this wrapped in jQuery. $($(this)) is the same as $(this) and therefore the extra call to $ is unnecessary in that case.

The answer is that it depends on the situation. In a lot of plugins, you call the plugin method on a jQuery object, which makes this already wrapped in jQuery!


$(this) adds the extra JQuery "sugar" to the element and then returns it. So the rule is simply that you only need to use $(this) if you want to call JQuery methods on it, and it hasn't already been passed through $(..).


It depends on what this refers to.

Inside an event handler function this refers to the HTML element the event is raised from. To perform jQuery operations on the element, you use $(this) to wrap the HTML element.

this in the scope of a plugin method refers to the jQuery selection object itself. Additionally, in plugins the jQuery method each is used to perform a function to each element in a jQuery selection. This is often the way plugins are written to provide a new method:

jQuery.fn.alertClasses = function()
{
    // "this" refers to the jQuery object, returned by $(...)
    if(this[0] === undefined)
        return this;

    this.each(function() { 
        // "this" now refers to an HTML element in the jQuery object
        alert(this.className)
    });

    // "this" refers to the jQuery object again
    return this;
}

In short, it's all about the context of the method. The jQuery documentation explains this concept whenever you're looking at methods which change the value of this.


Use $(this) if you need to access your Object as a jQuery Object. If you're referring to internal properties of your Object that you don't need jQuery for, just use this


As you noted:

$(this) -- returns jQuery object

this -- returns DOM object

this.whatever will return an attribute/function of the DOM object

$(this).whatever will return an attribute/function of the jQuery object


Use $(this) when jQuery offers a better interface for the functionality you need (which is most of the time for DOM manipulation).

I recommend using this when you have to (when there's no jQuery equivalent), or when the basic interface is simpler, like calling form.submit() rather than $('form').trigger('submit').

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜