Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - 如何在加载页面时运行函数?(How to run a function when the page is loaded?)

I want to run a function when the page is loaded, but I don't want to use it in the <body> tag.

(我想在页面加载时运行一个函数,但我不想在<body>标签中使用它。)

I have a script that runs if I initialise it in the <body> , like this:

(如果我在<body>初始化它,我会运行一个脚本,如下所示:)

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, eg this:

(但是我想在没有<body onload="codeAddress()">情况下运行它,我尝试了很多东西,例如:)

window.onload = codeAddress;

But it is not working.

(但它没有用。)

So how do I run it when the page is loaded?

(那么如何在加载页面时运行它?)

  ask by Claes Gustavsson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...