$(this) 和 this 有什么区别?

3

请问有人能解释一下它们之间的区别吗?

例如,我可以用“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);
});

重复:https://dev59.com/D3NA5IYBdhLWcg3wNa-T - Jørn Schou-Rode
4个回答

7

你的第二个例子不起作用,因为每次使用 $(this) 函数时,它都会返回一个唯一的jQuery对象:

var a = document.createElement('a');
var b = $(a);
var c = $(a);

现在,bc都是独特的jQuery实例。
console.log(c == b) // prints false

在使用jQuery的点击事件时,this是回调函数中的event.currentTarget,它是绑定了点击事件的HTML元素:

button.click(function(e) {
    console.log (e.currentTarget == this) // prints true
})

$(this)jQuery(this)是一个返回被包装在独特的jQuery对象中的HTML元素,并包含所有jQuery原型的函数。


7

this 是普通的 Javascript 对象。

$(this) 是一个被 jQuery 包装的元素。你可以使用它来调用 jQuery 方法。


哇!回复好快。谢谢,我现在明白了。 :) - Somebody

1

$(this) 创建了一个包含 this 的 jQuery 对象。 this 是表示被点击的按钮的 HTMLElement


1

这里有一个非常好的页面,详细解释了它并提供了示例。

(注意:这也是“jquery this”在谷歌上的第一个搜索结果)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接