gpt4 book ai didi

javascript - 将属性附加到 Javascript 中的冒泡事件对象

转载 作者:行者123 更新时间:2023-12-02 05:09:22 26 4
gpt4 key购买 nike

在 Chrome/Firefox 中,我可以将我的自定义属性附加到一个处理程序中的事件对象,并在同一事件的不同处理程序中读取它们,即使事件处理冒泡也是如此。

我不能在 IE 中做同样的事情。事件冒泡时,我的自定义属性丢失了。您知道对此是否有任何解决方案或解决方法吗?

以下是该问题的示例:

<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 测试)。

尝试下一个代码:

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;
});

我不确定,但也许,当请求 event 对象时,IE8 总是返回 new 对象,它包含与先前请求相同的属性/值。

关于javascript - 将属性附加到 Javascript 中的冒泡事件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7361869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com