javascript 手动 dispatchEvent DOMContentLoaded
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9153314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manually dispatchEvent DOMContentLoaded
提问by Robin Heggelund Hansen
Is there any way to manually fire the DOMContentLoaded
event? I'm trying to write a unit-test for some client-side JavaScript which does some stuff on the DOMContentLoaded
event.
有没有办法手动触发DOMContentLoaded
事件?我正在尝试为一些客户端 JavaScript 编写一个单元测试,它在DOMContentLoaded
事件上做一些事情。
The following did not work:
以下方法无效:
document.dispatchEvent("DOMContentLoaded")
or document.body.dispatchEvent("DOMContentLoaded")
document.dispatchEvent("DOMContentLoaded")
或者 document.body.dispatchEvent("DOMContentLoaded")
回答by Inversion
This works for me in Firefox:
这在 Firefox 中对我有用:
var DOMContentLoaded_event = document.createEvent("Event")
DOMContentLoaded_event.initEvent("DOMContentLoaded", true, true)
window.document.dispatchEvent(DOMContentLoaded_event)