jquery(this)
jQuery $(this) 用法详解
$(this) 是 jQuery 中常见的用法,用于将当前 DOM 元素包装成 jQuery 对象,便于调用 jQuery 提供的方法。以下是其核心用法和场景说明:
基本概念
this是 JavaScript 原生对象,指代当前触发事件的 DOM 元素。$(this)将原生this转换为 jQuery 对象,从而可以使用.css()、.attr()等 jQuery 方法。
常见场景
事件处理函数中

$("button").click(function() {
// 修改当前点击按钮的背景色
$(this).css("background-color", "red");
});
遍历元素时

$(".item").each(function() {
// 为每个元素添加 data-id 属性
$(this).attr("data-id", "123");
});
链式调用
$("div").hover(
function() {
$(this).addClass("active").fadeOut(200);
},
function() {
$(this).removeClass("active").fadeIn(200);
}
);
注意事项
- 在箭头函数中,
this指向可能不同,需谨慎使用。 - 直接调用原生 DOM 方法时,需通过
this而非$(this)(例如this.value)。
性能优化
- 若多次使用
$(this),可缓存为变量:$("a").click(function() { var $el = $(this); $el.hide(); $el.next().show(); });
与其他选择器结合
可通过 find()、children() 等方法进一步操作当前元素的子元素:
$("ul").click(function() {
$(this).find("li").toggleClass("highlight");
});






