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

JavaScript点击事件中e.target.name在子元素触发时返回undefined的原因及替代方案咨询

为什么点击按钮内图标时e.target.name返回undefined?

这个问题我之前也碰到过,其实核心原因和事件触发的目标元素以及HTML属性的规范有关,我来给你拆解下:

问题原因

  1. e.target指向实际点击的元素:当你点击按钮里的图标时,e.target对应的是<i>标签,而不是外层的<button>;点击按钮空白区域时,e.target才是<button>。
  2. name属性的适用范围有限:HTML规范里,name属性仅对表单相关元素(比如<button>、<input>、<select>这类)是标准属性,像<i>这类通用行内元素的name属性并不被浏览器认可为标准属性,所以即使你写了name="scissors",也无法通过e.target.name获取到值,自然返回undefined。

解决方案

这里有几个靠谱的解决思路,你可以根据需求选:

方案1:用e.currentTarget代替e.target

e.currentTarget始终指向绑定事件监听器的那个元素(也就是你的<button>),不管事件是从哪个子元素冒泡上来的。修改代码非常简单:

const scissorsEl = document.querySelector(".icon-scissors");
scissorsEl.addEventListener("click", (e) => {
  // 把e.target改成e.currentTarget
  state.setUserChoice(e.currentTarget.name);
  console.log("label:", e.currentTarget.name);
});
const state = {
  userChoice: "",
  setUserChoice(choice) {
    this.userChoice = choice;
  },
}

这个方案最省心,不需要修改HTML,直接改事件处理逻辑就行。

方案2:使用data-*自定义属性

如果不想依赖name属性,可以给元素加标准的自定义属性data-choice,这样所有元素都能支持:
首先修改HTML,给按钮添加属性(图标不需要,因为事件会冒泡到按钮):

<button class="icon icon-scissors" data-choice="scissors">
  <i class="fa-solid fa-hand-scissors"></i>
</button>

然后在JS里获取:

scissorsEl.addEventListener("click", (e) => {
  // 向上查找最近的带有data-choice属性的元素
  const choice = e.target.closest('[data-choice]').dataset.choice;
  state.setUserChoice(choice);
  console.log("label:", choice);
});

这种方式更符合HTML规范,自定义属性的语义也更清晰。

方案3:阻止图标元素的事件冒泡(不推荐)

你也可以给图标添加点击事件并阻止冒泡,但这样会增加不必要的代码,而且如果以后按钮里加了其他子元素,还要重复处理,所以不建议用这种方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 06:39:16