
本文详解为何在 jQuery 事件监听中使用箭头函数会导致 $(this) 失效,以及如何通过普通函数正确获取当前被点击元素的文本内容。
本文详解为何在 jquery 事件监听中使用箭头函数会导致 `$(this)` 失效,以及如何通过普通函数正确获取当前被点击元素的文本内容。
在 jQuery 中,为多个共享同一 class(如 .adressLine)的
? 问题根源:箭头函数没有自己的 this
箭头函数不绑定自身的 this,而是继承外层作用域的 this 值。在事件回调中,jQuery 原本会将 this 自动设置为当前触发事件的 DOM 元素(即被点击的 .adressLine),但箭头函数会忽略这一机制,使 this 指向外层(如全局对象或模块作用域),因此 $(this).text() 返回空字符串:
const adressLine = $('.adressLine');
adressLine.on('click', () => {
console.log('button clicked');
console.log($(this).text()); // ❌ this 不是当前 DOM 元素 → 空字符串
});
✅ 正确做法:使用普通函数(function 表达式或声明)
普通函数具有动态绑定的 this,jQuery 会在调用时将其设为当前事件目标元素:
const adressLine = $('.adressLine');
adressLine.on('click', function() { // ✅ 使用 function,非箭头函数
console.log('button clicked');
const text = $(this).text(); // ✅ this 指向被点击的 .adressLine 元素
console.log(text); // 输出该 div 的实际文本内容
});
? 提示:$(this) 是 jQuery 包装后的当前元素对象;若需原生 DOM 元素,可直接使用 this.textContent 或 this.innerText。
?️ 进阶建议(可选优化)
-
避免重复查询:若需多次操作当前元素,可缓存 $(this):
adressLine.on('click', function() { const $el = $(this); console.log($el.text()); $el.addClass('active'); // 示例:添加样式 }); -
使用事件委托(适用于动态添加的元素):
$(document).on('click', '.adressLine', function() { console.log($(this).text()); });
⚠️ 注意事项
- 类名拼写需一致:示例中为 '.adressLine'(注意 adress 非 address),请确保 HTML 中 class 名完全匹配;
- 确保 jQuery 已正确加载,且 DOM 加载完成后执行脚本(推荐包裹在 $(document).ready(...) 或 $(function(){...}) 中);
- 若元素内含 HTML 标签,.text() 只提取纯文本;如需包含 HTML,改用 .html()(注意 XSS 风险)。
掌握 this 在 jQuery 事件中的行为差异,是编写健壮前端交互逻辑的关键一步。始终牢记:事件处理器中需要动态 this 时,请勿使用箭头函数。











