Javascript event.target.name 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48991117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:17:53  来源:igfitidea点击:

event.target.name is undefined

javascripthtmlreactjs

提问by Nilos

I am trying to use e.target.name in react to set the state as I have done before, however e.target.name seems to be undefined for some reason and I can't figure out why, if any one has a suggestion it will be welcome. thanks!

我正在尝试使用 e.target.name 作为反应来设置状态,就像我之前所做的那样,但是 e.target.name 由于某种原因似乎未定义,如果有人有建议,我不知道为什么它会受到欢迎。谢谢!

<li 
    onMouseEnter = {this.handleMouseEnter.bind(this)}
    name ='HOME'
    id="some id"
    style={main.element}>HOME</li>

my event handler has only a debugger for me to play with

我的事件处理程序只有一个调试器供我使用

handleMouseEnter(e){
    debugger
}

and when i try to get the value of the name property i get undefined

当我尝试获取 name 属性的值时,我得到未定义

e.target
//<li name=?"HOME" id=?"some id" style=?"padding:? 10px;?">?HOME?</li>?
e.target.name
//undefined
e.target.id
//"some id"

回答by Sync

nameis an attribute and needs function getAttribute(...)to be fetched. As @Ele has pointed out, the suggested solution would be

name是一个属性,需要getAttribute(...)获取函数。正如@Ele 所指出的,建议的解决方案是

var name = e.target.getAttribute('name'); //'HOME'

回答by Ele

  • Form fields are the elements who must use the attribute name.
  • The JS engine will automatically set that attribute within the form elements (input, select, etc).
  • 表单域是必须使用属性的元素name
  • JS引擎将自动设置表单元素(内该属性inputselect等等)。

document.querySelector('li').addEventListener('click', function(e) {
  console.log('Directly: ' + e.target.name);// prints null
  console.log('Using getAttribute: ' + e.target.getAttribute('name')); // prints ele
});

document.querySelector('input').addEventListener('click', function(e) {
  console.log('Directly: ' + e.target.name);
  console.log('Using getAttribute: ' + e.target.getAttribute('name')); // prints ele
});
<input name="ele" placeholder="Click me!">
<li name="ele">Click me!</li>