我知道$(this)
会产生一个jQuery对象,但我经常(特别是在jQuery插件中)看到return this.whatever
的使用,一般的规则是什么?
谢谢
发布于 2009-11-12 16:02:43
这取决于this
指的是什么。
在事件处理程序中,函数this
引用引发事件的HTML元素。要在元素上执行jQuery操作,可以使用$(this)
包装HTML元素。
插件方法作用域中的this
引用jQuery选择对象本身。此外,在插件中,jQuery方法each
用于对jQuery选择中的每个元素执行一个函数。这通常是编写插件以提供新方法的方式:
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;
}
简而言之,这一切都与方法的上下文有关。每当您查看更改this
值的方法时,jQuery文档都会解释这一概念。
发布于 2009-11-12 15:50:27
当你想在'this‘上使用JQuery功能时,请使用$(this)
。
如果不想在“this”上使用JQuery功能,请使用“this”。
发布于 2009-11-12 15:52:10
$(this)
为您提供了包装在jQuery中的this
。$($(this))
与$(this)
相同,因此在这种情况下不需要额外调用$
。
答案是,这取决于情况。在许多插件中,您都是在jQuery对象上调用插件方法,这使得this
已经包装在jQuery中!
https://stackoverflow.com/questions/1723180
复制相似问题