event.target.name is undefined

前端 未结 2 470
刺人心
刺人心 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: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
    });
    
    
  • Click me!

提交回复
热议问题