jquery $this
jQuery 中的 $(this)
在 jQuery 中,$(this) 是一个常见的用法,用于引用当前操作的 DOM 元素。它通常用于事件处理程序或遍历方法中,表示当前上下文中的元素。
基本用法
$(this) 将当前 DOM 元素包装为一个 jQuery 对象,从而可以使用 jQuery 提供的方法。例如,在点击事件中:
$("button").click(function() {
$(this).hide(); // 隐藏当前点击的按钮
});
与 this 的区别
this是原生 JavaScript 对象,直接指向 DOM 元素。$(this)是 jQuery 对象,可以调用 jQuery 方法。
$("div").click(function() {
console.log(this); // 输出原生 DOM 元素
console.log($(this)); // 输出 jQuery 对象
});
常见应用场景
事件处理
在事件处理函数中,$(this) 通常指向触发事件的元素。
$("a").hover(function() {
$(this).css("color", "red");
}, function() {
$(this).css("color", "blue");
});
遍历操作
在 each() 方法中,$(this) 表示当前迭代的元素。
$("li").each(function() {
console.log($(this).text());
});
链式调用
$(this) 可以与其他 jQuery 方法链式调用。

$("p").click(function() {
$(this).addClass("highlight").fadeOut(1000);
});
注意事项
- 在嵌套函数或回调中,
this的上下文可能会变化,此时需要保存$(this)的引用。
$("div").click(function() {
var $self = $(this);
setTimeout(function() {
$self.css("background", "yellow");
}, 1000);
});
- 箭头函数会改变
this的绑定,因此不建议在 jQuery 事件处理中使用箭头函数。
// 错误示例
$("button").click(() => {
$(this).hide(); // 这里的 `this` 不会指向按钮
});
总结
$(this) 是 jQuery 中非常实用的工具,能够方便地操作当前上下文中的元素。理解其与原生 this 的区别,并注意上下文变化,可以更高效地使用它。






