最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
怎样正确获取被点击的同名 class 元素的文本内容
时间:2026-07-15 20:30:50 编辑:袖梨 来源:一聚教程网
本文详解为何在 jQuery 事件监听中使用箭头函数会导致 $(this) 失效,以及如何通过普通函数正确获取当前点击元素的内容。
本文详解为何在 jquery 事件监听中使用箭头函数会导致 `$(this)` 失效,以及如何通过普通函数正确获取当前点击元素的内容。
在使用 jQuery 绑定事件时,若多个元素共享同一 class(如 .adressLine),常需获取被点击的那个具体元素的文本内容。但初学者容易陷入一个典型误区:在事件回调中误用箭头函数,导致 $(this) 指向错误,最终返回空字符串。
❌ 错误写法:箭头函数破坏 this 绑定
const adressLine = $('.adressLine');adressLine.on('click', () => { console.log('button clicked'); var text = $(this).text(); // ⚠️ this 指向外层作用域(如 window),非当前 DOM 元素 console.log(text); // 输出空字符串或 undefined});
原因在于:箭头函数不绑定自己的 this,它会继承外层函数作用域的 this 值(通常为 window 或 undefined)。而 jQuery 的事件处理机制依赖于普通函数的动态 this 绑定——当事件触发时,jQuery 会将 this 显式设置为当前匹配的 DOM 元素(即被点击的 .adressLine 元素)。
✅ 正确写法:使用普通函数(function 表达式或声明)
const adressLine = $('.adressLine');adressLine.on('click', function() { // ← 普通函数,this 可被 jQuery 正确绑定 console.log('button clicked'); const text = $(this).text(); // ✅ this 指向当前被点击的 .adressLine 元素 console.log(text); // 输出该元素内纯文本内容(不含 HTML 标签)});
? 提示:你也可以使用 $(this).html() 获取包含 HTML 标签的完整内容,或 $(this).attr('data-text') 读取自定义属性值,视需求而定。
? 验证技巧:打印 this 和 $(this) 类型
可在回调中加入调试语句确认绑定是否生效:
adressLine.on('click', function() { console.log('Raw this:', this); // → HTMLDivElement 实例 console.log('jQuery this:', $(this)); // → jQuery 对象,含该元素 console.log('Text content:', $(this).text().trim()); // 推荐加 trim() 清除首尾空白});
⚠️ 注意事项与最佳实践
避免混用箭头函数与 this 事件上下文:jQuery、原生 addEventListener(需用 e.currentTarget)等均依赖函数级 this 绑定,箭头函数在此场景下不适用。
确保 DOM 已加载:将代码包裹在 $(document).ready() 或置于 <body> 底部,防止元素未就绪导致选择器返回空集。
-
考虑事件委托(进阶):若 .adressLine 是动态添加的元素,建议使用事件委托:
$(document).on('click', '.adressLine', function() { console.log($(this).text());});
掌握 this 在不同函数类型中的行为差异,是前端事件处理的关键基础。牢记:要访问被触发事件的当前元素,请始终在 jQuery 事件回调中使用普通函数。
相关文章
- Vegas如何制作打字机字幕效果 07-17
- 鲨鱼记账记错了怎样删除 07-17
- 《和平精英》湖心岛鱼竿怎么获得-特训岛钓鱼位置指南 07-17
- soulmate聊满8个字需要多长时间 07-17
- 熊猫办公网页版如何登录 07-17
- 简单搜索手机版怎样设置个性化推荐功能 07-17