jquery $ this
jQuery 中的 $(this)
在 jQuery 中,$(this) 是一个常见的用法,用于引用当前操作的 DOM 元素。this 在 JavaScript 中通常指向当前执行上下文的对象,而 $(this) 则是将 this 包装为 jQuery 对象,以便使用 jQuery 提供的方法。
基本用法
$(this) 通常在事件处理函数或回调函数中使用,表示触发事件的元素。例如:

$("button").click(function() {
$(this).css("background-color", "red");
});
这段代码会将点击的按钮背景色改为红色。
与普通 this 的区别
this是原生 JavaScript 对象,直接调用 DOM 方法。$(this)是 jQuery 对象,可以调用 jQuery 方法(如.css(),.hide()等)。
常见场景
-
事件处理:在事件回调中操作当前元素。

$("div").hover(function() { $(this).addClass("highlight"); }); -
遍历操作:在
.each()中引用当前元素。$("li").each(function() { console.log($(this).text()); }); -
链式调用:对当前元素进行多次操作。
$("p").click(function() { $(this).css("color", "blue").slideUp(); });
注意事项
- 避免在非 jQuery 上下文中误用
$(this)(如直接使用this即可的情况)。 - 确保
this的上下文正确(例如箭头函数会改变this的指向)。
通过 $(this),可以方便地结合 jQuery 的方法链和简化 DOM 操作。






