jquery中this
jQuery 中的 this
在 jQuery 中,this 是一个关键概念,通常指代当前操作的 DOM 元素。以下是关于 this 的详细说明和常见用法:
基本概念
this 在 jQuery 中通常指向当前事件的 DOM 元素。例如,在事件处理函数中,this 表示触发事件的元素。需要注意的是,this 是一个原生 DOM 对象,如果需要使用 jQuery 方法,需要用 $(this) 包装。
常见用法
事件处理中的 this
在事件处理函数中,this 指向触发事件的 DOM 元素。例如:
$("button").click(function() {
// this 指向被点击的 button 元素
console.log(this); // 输出原生 DOM 元素
console.log($(this)); // 转换为 jQuery 对象
});
遍历中的 this
在使用 .each() 方法遍历元素时,this 指向当前迭代的 DOM 元素:
$("li").each(function() {
// this 指向当前 li 元素
console.log($(this).text());
});
回调函数中的 this
在某些 jQuery 方法(如 $.ajax)的回调函数中,this 的指向可能不同。例如,在 $.ajax 的 success 回调中,this 默认指向 AJAX 请求的配置对象:
$.ajax({
url: "example.com",
success: function() {
console.log(this); // 指向 AJAX 配置对象
}
});
注意事项
this是原生 DOM 对象,直接调用 jQuery 方法会报错,必须用$(this)转换。- 在箭头函数中,
this的指向会发生变化(指向外层作用域),因此不建议在 jQuery 事件处理中使用箭头函数。
示例代码
以下是一个完整的示例,展示 this 在不同场景下的用法:

// 事件处理
$(".btn").click(function() {
$(this).hide(); // 隐藏点击的按钮
});
// 遍历
$(".item").each(function() {
console.log($(this).attr("id"));
});
// AJAX 回调
$.ajax({
url: "api/data",
context: document.body, // 修改回调中 this 的指向
success: function() {
$(this).append("<p>Data loaded</p>");
}
});
通过以上示例和说明,可以更好地理解 this 在 jQuery 中的行为和应用场景。






