在页面加载时自动运行 javascript 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27633885/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:44:26  来源:igfitidea点击:

Auto run javascript code on page load

javascript

提问by Khalid Kamal

How can I run javascript code just after page load, when page is loaded, it trigger, and when I go to another page it also trigger another piece of code for that page, how can I do it ?

如何在页面加载后立即运行 javascript 代码,加载页面时,它会触发,当我转到另一个页面时,它还会触发该页面的另一段代码,我该怎么做?

回答by sagar43

You can try

你可以试试

<!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>

Click here http://jsfiddle.net/NEfR2/

点击这里http://jsfiddle.net/NEfR2/

回答by facundofarias

document.ready()is a jQuery event. JQuery's document.ready()method gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.

document.ready()是一个 jQuery 事件。document.ready()一旦 DOM 准备好(这意味着浏览器已经解析了 HTML 并构建了 DOM 树),JQuery 的方法就会被调用。这使您可以在文档准备好进行操作时立即运行代码。

For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. However, IE can't safely fire until the document's readyState reaches “complete”, which is typically later.

例如,如果浏览器支持 DOMContentLoaded 事件(就像许多非 IE 浏览器一样),那么它将在该事件上触发。然而,IE 不能安全地触发,直到文档的 readyState 达到“完成”,这通常是更晚的。

You can find more info here(of course, this requires jQuery to be loaded)

您可以在此处找到更多信息(当然,这需要加载 jQuery)