如何在页面加载时运行函数? [英] How to run a function when the page is loaded?

查看:35
本文介绍了如何在页面加载时运行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在页面加载时运行一个函数,但我不想在 标签中使用它.

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:

function codeAddress() {
  // code
}

<body onLoad="codeAddress()">

但我想在没有 <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;

但它不起作用.

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

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

推荐答案

window.onload = codeAddress; 应该可以工作 - 这是一个演示,以及完整的代码:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆