Javascript alert('你好'); 在 pageLoad() 函数中工作?

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

Does alert('hello'); work in pageLoad() function?

javascript

提问by Valamas

Alert does not work in pageLoad, why? thanks

警报在 pageLoad 中不起作用,为什么?谢谢

<html>
<head>  
    <script type="text/javascript">
        function pageLoad()
        {
            alert('hello');
        }
    </script>
</head>
<body />
</html>

Problem found:Dave Ward suggests that since my page does not have a script manager (which calls PageLoad for me). that is the reason I was puzzled. I never realised I had to call it for myself when there was no script manager.

发现问题:Dave Ward 建议,因为我的页面没有脚本管理器(它为我调用 PageLoad)。这就是我感到困惑的原因。当没有脚本管理器时,我从未意识到我必须为自己调用它。

采纳答案by user113716

Yes, but you need to invoke it somewhere:

是的,但您需要在某处调用它:

<script type="text/javascript">

    function pageLoad()
    {
        alert('hello');
    }

    pageLoad();  // invoke pageLoad immediately

</script>

Or you can delay it until all content is loaded:

或者您可以延迟它直到加载所有内容:

<script type="text/javascript">

    function pageLoad()
    {
        alert('hello');
    }

    window.onload = pageLoad;  // invoke pageLoad after all content is loaded

</script>

回答by generalhenry

alternatively you can self invoke it

或者你可以自己调用它

(function pageLoad() {
  alert('hello');
})();

回答by Luke Bennett

pageLoadis never being called. Try the following:

pageLoad永远不会被调用。请尝试以下操作:

<html>
<head>  
    <script type="text/javascript">
        function pageLoad()
        {
            alert('hello');
        }
        window.onload = pageLoad;
    </script>
</head>
<body />
</html>

Note a better way of doing this is by using jQueryand the following syntax:

请注意,更好的方法是使用jQuery和以下语法:

$(window).load(pageLoad);

You could also use an alternative Javascript framework as most provide a similar way of doing this. They all take account of a number of issues related to attaching to event handlers.

您也可以使用替代的 Javascript 框架,因为大多数框架都提供了类似的方法。它们都考虑了与附加到事件处理程序相关的许多问题。

回答by bbosak

Try:

尝试:

<html>
<head>  
<script type="text/javascript">
    function pageLoad()
    {
        alert('hello');
    }
</script>
</head>
 <body onload="pageLoad()" />
 </html>