[英]run javascript functions when the page loads
I have several JavaScript functions that need to run when the page loads to fetch content. 页面加载以获取内容时,我需要运行一些JavaScript函数。 I have tried to use window.onload to call the function but it hasn't worked.
我试图使用window.onload来调用该函数,但是它没有起作用。
Basically, need to run several functions after the page finishes loading but only once. 基本上,页面完成加载后需要运行多个功能,但仅运行一次。
I have this so far but it didn't work 到目前为止,我有这个,但是没有用
<script language="javascript">
window.onload=serverstats
window.onload=latestnews
</script>
Here is your main issue: 这是您的主要问题:
window.onload=serverstats #sets window.onload to serverstats
window.onload=latestnews #sets window.onload to latestnews and removes the reference to serverstats
You can fix this by doing: 您可以通过以下方法解决此问题:
oldOnload = window.onload;
window.onload=function() {
oldOnload();
serverstats();
latestnews();
};
However, as the question is tagged with JQuery, I would recommend using it and doing: 但是,由于问题是用JQuery标记的,因此我建议使用它并执行以下操作:
$(document).ready(function() {
serverstats();
latestnews();
});
You can also handle both by using the following code: 您还可以使用以下代码来处理这两种情况:
window.addEventListener("load", serverstats);
window.addEventListener("load", latestnews);
This doesn't work in IE8 and earlier though, which use: 这在IE8和更早版本中不起作用,但使用:
window.attachEvent("onload", serverstats);
window.attachEvent("onload", latestnews);
You're overwriting the onload
value. 您正在覆盖
onload
值。 Write a function that calls both of them instead. 编写一个调用它们两者的函数。
window.onload = function() {
serverstats();
latestnews();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.