$(this)和this,有什么区别? [英] $(this) and this, what difference?
问题描述
有人可以解释一下,他们之间有什么区别?
Could someone please explain a bit, what difference between them?
例如,我可以使用"that"来做到这一点:
For example I could do that with "that":
var bar;
button.click(function () {
if (bar == this) {
alert('same');
}
bar = this;
});
并且不能使用$(that):
and couldn't with $(that):
var bar;
button.click(function(){
if(bar == $(this)) {alert('same');}
bar = $(this);
});
推荐答案
您的第二个示例不起作用,因为每次您使用$(this)
函数时,它都会返回一个唯一 jQuery对象:>
Your second example doesnt work, because every time you use the $(this)
function, it returns an unique jQuery Object:
var a = document.createElement('a');
var b = $(a);
var c = $(a);
现在, b 和 c 都是唯一的jQuery实例.
Now, b and c are both unique jQuery instances.
console.log(c == b) // prints false
使用jQuery click事件时,this
是回调中的event.currentTarget,它是绑定单击的HTML元素:
When using jQuery click events, this
is the event.currentTarget in the callback, which is the HTML element that bound the click:
button.click(function(e) {
console.log (e.currentTarget == this) // prints true
})
$(this)
或jQuery(this)
是一个函数,该函数返回包装在唯一jQuery对象中的HTML元素,并包含所有jQuery原型.
$(this)
or jQuery(this)
is a function that returns the HTML element wrapped in a unique jQuery Object, and contains all jQuery prototypes.
这篇关于$(this)和this,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!