gpt4 book ai didi

javascript - 无法在 Internet Explorer 中将属性分配给 window.event(或数据属性)

转载 作者:行者123 更新时间:2023-11-30 18:45:49 25 4
gpt4 key购买 nike

所以,我正在使用事件冒泡来捕获子 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 中不起作用。我尝试在事件对象上使用“数据”属性,但这只允许使用字符串。

有没有其他方法可以在不对每个子对象使用闭包的情况下实现相同的功能?

最佳答案

不漂亮,但应该可以。 Box9 the magnificent建议我忽略了一些事情,也就是说,如果某些东西在它冒泡到 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";
};

关于javascript - 无法在 Internet Explorer 中将属性分配给 window.event(或数据属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5545986/

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