javascript 如何处理 <head> 标签中的 body onload 事件

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

How to handle body onload event in <head> tag

javascriptjspjavascript-eventssitemesh

提问by Raje

I am using sitemesh in our application. In decorator jsp i have addded in head and on body tag <body onload="<decorator:getProperty property='body.onload'/>" >. so i want to handle body onload on my jsp page. I have added following things

我在我们的应用程序中使用了 sitemesh。在装饰器 jsp 中,我添加了 head 和 body 标签 <body onload="<decorator:getProperty property='body.onload'/>" >。所以我想在我的jsp页面上处理body onload。我添加了以下内容

<script type="text/javascript">
    function init() {
        alert("hi");
    }
</script>
</head>
<body onload="javascript:init();">

But init () does not worked in my jsp page.

但是 init() 在我的 jsp 页面中不起作用。

采纳答案by beta

try this

试试这个

<script type="text/javascript">
    function init() {
        alert("hi");
    }
</script>
</head>
<body onload="init();">

回答by lonesomeday

Why not just stick it all into the scriptelement? Much cleaner than mucking about with element attributes:

为什么不把它全部粘贴到script元素中?比处理元素属性要干净得多:

window.onload = function() {
    alert('hi');
};

Or, alternatively, keeping the initdeclaration:

或者,或者,保留init声明:

window.onload = init;