You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多个同class的div点击时,使用$(this)获取内容返回空值的原因

问题分析与解决

为什么第一次拿到所有元素的文本?

你定义的adressLine是jQuery选中的所有.adressLine元素的集合,调用adressLine.text()时,jQuery会自动把这个集合里所有元素的文本内容拼接起来返回,所以你看到的是所有div的文本总和。

为什么用箭头函数时$(this).text()返回空?

箭头函数不会绑定自己的this,它的this继承自外层作用域(比如这里是全局window对象),而非被点击的div元素。所以$(this)指向的不是你点击的目标,自然拿不到文本,返回空字符串。

正确写法有两种:

  1. 改用普通函数作为事件处理函数,此时this会指向被点击的DOM元素:
const adressLine = $('.adressLine');
adressLine.on('click', function() {
    console.log('button clicked');
    var text = $(this).text();
    console.log(text);
});
  1. 继续用箭头函数,但通过事件对象的target属性获取点击元素:
const adressLine = $('.adressLine');
adressLine.on('click', (e) => {
    console.log('button clicked');
    var text = $(e.target).text();
    console.log(text);
});

内容的提问来源于stack exchange,提问作者Fefe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:02:39