【问题标题】:I cant the value of the element name - e.target.name returns undefined我无法获取元素名称的值 - e.target.name 返回 undefined
【发布时间】:2021-11-04 17:00:36
【问题描述】:

在 onClick 事件中,我在函数中捕获事件(e) 并尝试获取被点击元素的名称

const ClickEvent = (e) => {
console.log(e.target.name) -> undefined
}

<svg>
<text onClick={ClickEvent} name="line1">
 hello world
</text>
</svg>

【问题讨论】:

  • 你在这里使用 React 吗?
  • 是的,这有什么不同吗?

标签: javascript reactjs svg


【解决方案1】:

DOM 属性并不总是可用作元素的直接命名属性。我建议你使用the getAttribute() method 来获取你想要的属性值。

console.log(e.target.getAttribute('name'))

【讨论】:

    【解决方案2】:

    最好的选择是使用 getAttributes 方法,因为 DOM 有时会有点挑剔。

    const ClickEvent = (e) => {
       console.log(e.target.getAttribute('name'))
    }
    

    更多参考类似问题:event.target.name is undefined

    【讨论】:

      【解决方案3】:

      没有e.target.name方法,试试e.target,查看控制台找到你想要的方法。

      我猜你的意思是e.target.localName

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        相关资源
        最近更新 更多