jquery this
jQuery 中的 this 用法
在 jQuery 中,this 是一个常见的引用,通常指向当前操作的 DOM 元素。以下是几种常见的使用场景和注意事项:
事件处理函数中的 this
在 jQuery 事件处理函数中,this 指向触发事件的 DOM 元素。例如:
$("button").click(function() {
// this 指向被点击的 button 元素
$(this).css("background-color", "red");
});
遍历函数中的 this
在 jQuery 的遍历方法(如 each)中,this 指向当前迭代的 DOM 元素:
$("li").each(function() {
// this 指向当前迭代的 li 元素
console.log($(this).text());
});
将 this 转换为 jQuery 对象
this 是原生 DOM 元素,若要使用 jQuery 方法,需用 $(this) 包装:
$("div").click(function() {
// 错误:this.css() 会报错,因为 this 不是 jQuery 对象
// 正确:$(this) 转换为 jQuery 对象
$(this).css("border", "1px solid black");
});
箭头函数中的 this
箭头函数会继承外层作用域的 this,因此在 jQuery 事件中慎用:
$("button").click(() => {
// 箭头函数中的 this 可能不是预期的 button 元素
console.log(this); // 可能是 window 或其他上下文
});
与其他方法的结合
this 可以与其他 jQuery 方法结合使用,例如 find、parent 等:

$(".container").click(function() {
// 在当前元素内查找子元素
$(this).find(".child").hide();
});
注意事项
- 确保在需要时用
$(this)包装原生 DOM 元素。 - 避免在箭头函数中使用
this处理 jQuery 事件。 this的值取决于调用上下文,尤其在异步操作中需谨慎。






