问题
I want to know why Mozilla and Chrome have other value of e.target. I prepared this example for you.
https://jsfiddle.net/qdthnmdx/
In the Mozilla e.target has value:
<button type="button">
But in the Chrome this is:
<span>Sometext</span>
Is it some bug?
回答1:
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
回答2:
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>
来源:https://stackoverflow.com/questions/41841688/different-value-e-target-in-browers