如何在页面加载时运行一个函数? [英] How to run a function when the page is loaded?
本文介绍了如何在页面加载时运行一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在页面加载时运行一个函数,但我不想在< body>
标记中使用它。
我有一个运行脚本,如果我在< body>
中初始化脚本,如下所示:
function codeAddress(){
// code
}
< body onLoad =codeAddress()> <
但是我想运行它而没有< body onLoad =codeAddress ()>
,我尝试了很多东西,例如这个:
window.onload = codeAddress;
但它不起作用。
那么如何在页面加载时运行它?
解决方案
window.onload = codeAddress;
应该工作 - 这里有一个演示和完整的代码:
<!DOCTYPE html>< html> < HEAD> <标题>试验< /标题> < meta http-equiv =Content-Typecontent =text / html; charset = utf-8/> < script type =text / javascript>函数codeAddress(){alert('ok'); } window.onload = codeAddress; < /脚本> < /头> <身体GT; < / body>< / html>
$ b
<!DOCTYPE html>< html> < HEAD> <标题>试验< /标题> < meta http-equiv =Content-Typecontent =text / html; charset = utf-8/> < script type =text / javascript>函数codeAddress(){alert('ok'); }< / script> < /头> < body onload =codeAddress();> < / body>< / html>
I want to run a function when the page is loaded, but I don’t want to use it in the <body>
tag.
I have a script that runs if I initialise it in the <body>
, like this:
function codeAddress() {
// code
}
<body onLoad="codeAddress()">
But I want to run it without the <body onLoad="codeAddress()">
and I have tried a lot of things, e.g. this:
window.onload = codeAddress;
But it is not working.
So how do I run it when the page is loaded?
解决方案
window.onload = codeAddress;
should work - here's a demo, and the full code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
</script>
</head>
<body onload="codeAddress();">
</body>
</html>
这篇关于如何在页面加载时运行一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文