有人可以解释一下,他们之间有什么区别?
例如,我可以使用“ 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 click事件时,
this
是回调中的event.currentTarget,它是绑定单击的HTML元素:button.click(function(e) {
console.log (e.currentTarget == this) // prints true
})
$(this)
或jQuery(this)
是一个函数,该函数返回包装在唯一jQuery对象中的HTML元素,并包含所有jQuery原型。