我是jquery的新手。我想知道this
和$(this)
之间的区别。假设我做了一个像这样的函数调用
$.fn.column = function() {
var $td = this;
var $td1 = $(this);
}; //end of $.fn.column = function()
$('#FaqGridForm\\:faqGrid tr td').column();
当我使用firebug时,两个变量都是[td]
。那么这两者之间有什么区别呢?
答案 0 :(得分:3)
在jQuery插件中,this
指向所有匹配元素的jQuery集合。在此上下文中使用$(this)
已过时,不鼓励。
在事件处理程序的上下文中,this
指向触发事件的DOM元素。 $(this)
将DOM元素包装在jQuery对象中,以便jQuery方法可用。
代码示例:
$.fn.plugin = function() { alert(this); };
$('selector').plugin(); //Alerts [object Object] = a jQuery object.
$('body').click(function() {
alert(this); // [object HTMLBodyElement]
alert($(this));// [object Object] (a jQuery object)
});
答案 1 :(得分:1)
在这种情况下,没有真正的区别。由于你已经扩展了jQuery,this
已经是jQuery的一个实例,所有$(this)
都会将它再次传递给jQuery,这是不必要的。
然而,在这种情况下:
$("#someElem").click(function() {
//this is now a reference to a DOM element:
console.log(this instanceof jQuery); //false
console.log(this.val()); //TypeError
});
您经常需要将this
传递给jQuery,以便在其上使用jQuery方法:
$("#someElem").click(function() {
console.log($(this) instanceof jQuery); //true
console.log($(this).val()); //Prints value
});
答案 2 :(得分:0)
this
是有问题的原生DOM元素。您可以在其上使用完整的DOM方法。
$(this)
是包装在jQuery对象中的本机DOM元素,因此您可以访问jQuery在其框架中提供的所有函数,以根据需要修改元素。您还可以使用以下命令通过jquery对象访问DOM元素:
$("#myElement")[0]
更新
这显然适用于在外部函数中编写jQuery。 Rob W是正确的,因为您的示例使用了插件,因此this
将引用包含元素的jQuery对象。