我正在尝试使用 JavaScript 创建自定义事件。
我有一个带有运行 Internet Explorer 9 的 Web 浏览器的 WPF 应用程序。
代码:
var evt = document.createEvent("Event");
evt.initEvent("readerstatechanged", true, false);
window.dispatchEvent(evt);
错误:
我也尝试过:
var evt = new Event("Event");
错误:
您知道如何使用 IE 9 创建自定义事件吗?
编辑:
我用 createEventObject 进行了更改,但“InitEvent”不起作用:
var evt = document.createEventObject("Event");
evt.initEvent("printerstatechanged", true, false);
window.dispatchEvent(evt);
然后我需要像这样使用attachEvent:
window.attachEvent('printerstatechanged', function (e) {
//Do something
});
最佳答案
IE9 支持 DOM3 事件,因此您可以创建和 Hook 自定义事件。这是一个完整的示例,适用于 IE9 和任何其他 DOM3 兼容的浏览器: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>IE9+ Custom Event</title>
</head>
<body>
<script>
(function() {
// Hooking the event, in this case on documentElement
document.documentElement.addEventListener("readerstatechanged", function() {
display("readerstatechanged received");
});
// Creating it
display("Creating");
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("readerstatechanged", true, false, {});
// Could put custom data here -------------------------^^
// Firing it on documentElement
display("Firing");
document.documentElement.dispatchEvent(evt);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
它在 IE8 中不起作用,但正如您所强调的 IE9...
如果您的网站显示在名称严重错误的“兼容性 View ”中,IE 会关闭这些标准功能,从而使其与现实世界的兼容性降低而不是提高。我认为,对 Intranet 站点使用“兼容性 View ”是默认设置,这很愚蠢。您可以通过向 head
部分添加 meta
标记来向 IE 保证您确实知道自己在做什么:
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
关于Javascript 使用 IE9 创建事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361387/