javascript - 页面加载时如何运行函数?

标签 javascript html onload

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

如果我在 <body> 中初始化它,我就会运行一个脚本。 ,像这样:

function codeAddress() {
  // code
}
<body onLoad="codeAddress()">

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

window.onload = codeAddress;

但它不起作用。

那么在页面加载的时候如何运行呢?

最佳答案

window.onload = codeAddress; 应该可以工作 - here's a demo ,以及完整的代码:

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

关于javascript - 页面加载时如何运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4842590/

相关文章:

javascript - Startswith 函数用于搜索数组

javascript - 使用javascript在本地保存的Keydown事件

html - 下面的 Div 到另一个显示 :inline-block attribute

jquery - 我如何让这个导航在 iphone 和 ipad 上工作,尽管它是响应式的

php - 第一个主体 onload 函数或 PHP 会发生什么?

javascript - 引用和更改容器内 HTML 按钮的属性

javascript - 如何检索 Javascript 对象名称数组

javascript - 设置一个等于当前所选选项的变量

javascript - jquery书架 slider 修改

php - 将 PHP 变量传递给 onLoad (JS)