有人可以解释一下,它们之间有什么区别吗?
例如,我可以用“that”来做到这一点:
var bar;
button.click(function () {
if (bar == this) {
alert('same');
}
bar = this;
});
并且不能使用 $(that):
var bar;
button.click(function(){
if(bar == $(this)) {alert('same');}
bar = $(this);
});
最佳答案
您的第二个示例不起作用,因为每次您使用 $(this)
函数时,它都会返回一个唯一 jQuery 对象:
var a = document.createElement('a');
var b = $(a);
var c = $(a);
现在,b 和 c 都是唯一的 jQuery 实例。
console.log(c == b) // prints false
使用 jQuery 点击事件时,this
是回调中的 event.currentTarget,即绑定(bind)点击的 HTML 元素:
button.click(function(e) {
console.log (e.currentTarget == this) // prints true
})
$(this)
或 jQuery(this)
是一个函数,它返回包装在唯一 jQuery 对象中的 HTML 元素,并包含所有 jQuery 原型(prototype)。
关于jquery - $(this) 和 this 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2295283/