如何在页面加载完成时从 HTML 文档正文调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5914613/
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
How to call javascript function from body of HTML document on pageload-complete
提问by Casey Flynn
I have some javascript (code to initialize google maps if you're interested) that I'm forced to include within the <body></body>
tags of an html document and I would like to have one of my methods trigger on page-load complete. The catch is that I don't have access to the <body>
html tag, so I can't do:
我有一些 javascript(如果您感兴趣,用于初始化 google 地图的代码),我被迫将其包含在<body></body>
html 文档的标签中,并且我希望我的方法之一在页面加载完成时触发。问题是我无权访问<body>
html 标签,所以我不能这样做:
<body onload="foo()">
Is there any way to accomplish this? I realize this is a ridiculous scenario. Thanks!
有什么办法可以做到这一点吗?我意识到这是一个荒谬的场景。谢谢!
回答by Felix Kling
Depending on when the code is run, attach the handler with JavaScript:
根据运行代码的时间,使用 JavaScript 附加处理程序:
if(window.onload) {
var _existing = window.onload;
window.onload = function() {
_existing();
foo();
};
}
else {
window.onload = foo;
}
As you seem to have no control over the page we have to be a bit more careful. Other JavaScript might already have set an event handler. To be a good citizen, we don't just overwrite the event handler, but keep a reference to it in case it exists.
由于您似乎无法控制页面,因此我们必须更加小心。其他 JavaScript 可能已经设置了事件处理程序。为了成为一个好公民,我们不仅要覆盖事件处理程序,还要保留对它的引用,以防它存在。
However other JavaScript code could overwrite this again.
然而,其他 JavaScript 代码可能会再次覆盖它。
The best way would be to use the more advanced event handling methods addEventListener
(W3C) and attachEvent
(IE).
最好的方法是使用更高级的事件处理方法addEventListener
(W3C) 和attachEvent
(IE)。
For more information about event handling I suggest to read the excellent articles on quirksmode.org.
有关事件处理的更多信息,我建议阅读quirksmode.org 上的优秀文章。
回答by SRM
You can programattically attach events using the DOM.
您可以使用 DOM 以编程方式附加事件。
// Function to add event listener to body
function addLoadFn()
{
var body = document.getElementById("body");
body.addEventListener("load", myOnloadListener, false);
}
回答by 2grit
window.onload = foo;
function foo(){
alert("page loaded!");
}