无法在 Internet Explorer 中为 window.event(或数据属性)分配属性

Can't assign properties to window.event (or data property) in Internet Explorer

本文关键字:数据属性 属性 分配 event window Internet Explorer 中为      更新时间:2023-09-26

所以,我正在使用事件冒泡来捕获子 DOM 事件... 我正在将点击事件附加到div包装器,并将点击事件附加到该包装器的子包装器......这样:

<div onclick="foo();">
    <div onclick="bar();">
        Hello World!
    </div>
</div>
function foo() {
    alert(window.event.abc.one);
};
function bar() {
    window.event.abc = {one: "23"};   
};

如您所见,我正在为abc分配一个自定义对象。 我使用它作为将消息发送到链上更靠后的点击处理程序的一种方式......并避免在每个子元素上使用闭包。 在其他浏览器中,您可以将任何您喜欢的内容分配给event对象...这效果很好。

但是(当然),这在IE中不起作用。 我尝试在事件对象上使用"data"属性,但这只允许字符串。

还有其他方法可以在不对每个子对象使用闭包的情况下完成相同的功能吗?

不漂亮,但这应该有效。Box9 宏伟的建议是我忽略的,那就是,如果某些东西在冒泡之前设置了一个属性bar()(例如,你内部div的后代上的事件处理程序),它将被覆盖。

var msg = {};
// When the event bubbles up to document, we'll reset it to an empty object
// literal, ready for new information to be attached to it.
document.onclick = function()  { msg = {} };
function foo() {
    alert(msg.one);
};
function bar() {
    // Assign this property only, so if something else had attached a property
    // to `msg`, it will remain intact.
    msg.one = "23";   
};