在Javascript中将属性附加到冒泡的事件对象 [英] Attaching properties to bubbled event object in Javascript
问题描述
在Chrome / Firefox中,我可以将自定义属性附加到一个处理程序中的事件对象,并在同一事件的不同处理程序中读取它们,即使事件处理已冒泡。
In Chrome/Firefox I can attach my custom properties to an event object in one handler and read them in a different handler for the same event even if the event handling is bubbled up.
我不能在IE中做同样的事情。事件冒泡时我的自定义属性丢失了。
您知道是否有任何解决方案或解决方法吗?
I cannot do the same in IE. My custom property is lost while event is bubbled up. Do you know if there's any solution or workaround to this?
以下是该问题的示例:
<div id="div1">
<input type="button" value="Foo" id="button1">
</div>
<script>
function attach(el, event, fn) {
if (el.addEventListener) {
el.addEventListener(event, fn);
} else if (el.attachEvent) {
el.attachEvent('on'+event, fn);
}
}
attach(document.getElementById("button1"), 'click', function (event) {
event.abc = "done";
return true;
});
attach(document.getElementById("div1"), 'click', function (event) {
alert(event.abc);
return true;
});
</script>
推荐答案
根据我的测试你不能添加属性IE中的事件对象(已测试IE8)。
According with my test you cannot add property to event object in IE (IE8 tested).
尝试下一个代码:
attach(document.getElementById("button1"), 'click', function (ev) {
//ev=ev||event;
//ev.abc = "done";
// next lines show you why you cannot save properties in event object
var xx1=event;
var xx2=event;
alert(xx1===xx2); // // showed *false* in IE8, but expected *true*
return true;
});
我不确定但是,当事件
请求对象,IE8始终返回 new 对象,该对象包含与先前请求相同的属性/值。
I am not sure but maybe, when event
object is requested, IE8 always return new object, that contains same properties/values as previous requested.
这篇关于在Javascript中将属性附加到冒泡的事件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!