jquery获取this的值
获取 this 的值
在 jQuery 中,this 的值通常指向当前 DOM 元素。可以通过以下方法获取或操作 this 的值:
直接使用 this
在事件处理函数中,this 默认指向触发事件的 DOM 元素:

$('button').click(function() {
console.log(this); // 输出触发点击事件的 button 元素
});
转换为 jQuery 对象
如果需要使用 jQuery 方法操作 this,可以将其包装为 jQuery 对象:
$('button').click(function() {
$(this).addClass('active'); // 为当前元素添加类名
});
箭头函数中的 this
箭头函数不会改变 this 的指向,因此在 jQuery 事件处理中需谨慎使用:

$('button').click(() => {
console.log(this); // 可能指向 window 或其他上下文
});
传递 this 给其他函数
可以在调用其他函数时显式传递 this:
$('button').click(function() {
handleClick(this);
});
function handleClick(element) {
$(element).hide();
}
结合 event.target
事件对象中的 target 属性也可以获取触发事件的元素:
$('button').click(function(event) {
console.log(event.target); // 与 this 效果相同
});
注意事项
- 在普通函数中,
this动态绑定到触发事件的元素。 - 使用
$(this)可调用 jQuery 方法,而直接使用this是原生 DOM 对象。 - 箭头函数会继承外层
this,可能导致预期外的结果。






