event.target.name is undefined

前端 未结 2 469
刺人心
刺人心 2020-12-31 09:32

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

相关标签:
2条回答
  • 2020-12-31 10:20

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

    var name = e.target.getAttribute('name'); //'HOME'
    
    0 讨论(0)
  • 2020-12-31 10:35
    • 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).

    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>


    0 讨论(0)
提交回复
热议问题