If you try this in Internet Explorer you can see that the dispatched event is not unique during开发者_开发问答 bubbling:
var x;
myinnerdiv.onclick = function() { x = window.event; };
myparentdiv.onclick = function() { alert(x === window.event); };
// false, but should be the same!
Using the equivalent standards-based method:
var x;
myinnerdiv.onclick = function(ev) { x = ev; };
myparentdiv.onclick = function(ev) { alert(x === ev); };
// true: same event, retargeted
Is there a way to uniquely identify an event in code to work around this lack of functionality?
window.event
is not a data value but a getter function to create event objects. Much like most
of the DOM properties are not data values but accessor functions.
You can even do them next to each other:
div.onclick = function() {
var a = window.event;
var b = window.event;
alert( a === b ) // false
};
Anyway, just make your own function:
window.getEvent = (function() {
var e = {};
return function() {
var cur = window.event;
if( cur.type === e.type &&
cur.srcElement === e.srcElement &&
cur.clientX === e.clientX &&
cur.clientY === e.clientY &&
cur.keyCode === e.keyCode ) {
return e.evt;
}
e.type = cur.type;
e.srcElement = cur.srcElement;
e.clientX = cur.clientX;
e.clientY = cur.clientY;
e.keyCode = cur.keyCode;
e.evt = cur;
return cur;
};
})();
myinnerdiv.onclick = function () {
var event = getEvent();
event.myCustomProp = 3;
};
myparentdiv.onclick = function () {
var event = getEvent();
alert( event.myCustomProp === 3 );
};
It assumes that these 5 values are enough to see if the event objects represent the same event, which seems reasonable to me.
Test page here, precisely click the text 'asd' (red colored), as the html is:
<div id="myparentdiv">
daa
<div id="myinnerdiv">asd</div>
daa
</div>
If you want something that works for sure then just use jQuery, you basically have to create an entire event model from scratch to do this more cleanly (and always use that event model's API).
A simple way: just compare event1.timeStamp and event2.timeStamp
精彩评论