这vs $(这个)
可能重复:
jQuery $(this)vs this
我是新手,并试图让我的概念正确。 已经有很多使用“ this
”和“ $(this)
”的$(this)
。 有人可以解释我们使用两个不同的“这个”的区别和条件吗?
在jQuery函数中, this
通常是指您正在处理的实际DOM元素,而$(this)
返回一个包装元素的jQuery对象。
在JavaScript中, this
总是指当前范围。 jQuery的许多函数都会将该范围设置为您正在使用的元素。
例如
$("#someElement").click(function() { this; // the element itself $(this); // a jQuery wrapper-object around the element });
关键是,jQuery对象具有所有jQuery函数(如.detatch()
或.detatch()
.prependTo()
等),而DOM元素是浏览器提供的。 在上面的示例中,如果调用document.getElementById("someElement")
,则元素将与您获得的元素完全相同
$(this)
引用一个jquery对象, this
在当前范围内引用this
$(this)
是一个jQuery对象。 this
是指当前范围内的值。 当您想要将触发事件的元素转换为jQuery对象时,通常在回调中使用$(this)
。 您可以对几乎任何DOM元素执行此操作,因此$(document.getElementById("#myElement"))
也是有效的,并且是一个jQuery对象,表示ID为“myElement”的DOM元素。