different value e.target in browers [duplicate]

有些话、适合烂在心里 提交于 2019-12-06 06:07:10

You have to know that every browser have their own implementation of the specificacion from JavaScript, here i have diferent result of your code for you even on Internet explore and google Chrone exist difference:

IE 11:

Google Chrome:

For more clarification in what is ECMA Specs is see: http://www.ecma-international.org/publications/standards/Ecma-262.htm

event.target is not different in browsers.

event.target is a reference to the object that dispatched the event. as you are attaching to the button,it is also attached to span element too. so when you hit on span,it is showing span node and on button it is showing button which is right, but this behaviour is more obvious on chrome but not on mozilla.

If you just want to attach an event on the button element. you can consider doing as the following

If you want button to be displayed on both button and span click , you might consider of using currentTarget here.

currentTarget always refers to the element to which the event handler has been attached.

I guess it could be useful here.

check this snippet

document.querySelector("button").addEventListener("click", function(e) {
		console.log(e.currentTarget.nodeName);
});
button {
  border: 1px solid;
  background: 0;
  padding:10px;
}
span {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div id="id-div">
  <button type="button">
    <span>Sometext</span>
  </button>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!