将 HTML <body>onLoad 事件会覆盖 javascript 窗口的 onload 事件吗? [英] will HTML <body> onLoad events overwrite javascript window onload event?
问题描述
我有一个 HTML 页面,并且一个 javascript 函数附加到 onLoad 事件.
I have a HTML page and a javascript function is attached to the <body>
onLoad event.
我想在页面加载时显示一个消息对话框.由于某些原因,我无法编辑附加到此 onLoad 事件的 javascript 函数.
I wanted to show up a message dialog when the page loads. I cannot edit the javascript function attached to this onLoad event due to some reasons.
所以我用一个函数创建了一个新的 javascript 文件,它将显示消息对话框.然后我在我的javascript文件中添加了这一行
So I created a new javascript file with a single function which will show the message dialog. Then I added this line in my javascript file
window.onload = onPageLoad;
onPageLoad()
是我的函数,可以显示消息对话框.
onPageLoad()
is my function which could show the message dialog.
我使用脚本标签在我的 HTML 中附加了这个 javascript 文件.当我运行这个 HTML 文件时,onPageLoad()
函数没有被调用.
I attached this javascript file in my HTML using script tag. When I run this HTML file, onPageLoad()
function is not getting called.
我想知道标签,onLoad事件是否覆盖了window的onload.如果是这样,有人可以帮助我以某种方式实现此功能.
I want to know whether <body>
tag, onLoad event overrides the window onload. If so, can someone help me in implementing this functionality somehow.
请记住,我无法编辑我的 HTML 文件,我只能编写新的 javascript 文件.谢谢.
Please keep in mind that I could not edit my HTML file and I could write only new javascript file. Thanks.
推荐答案
取决于浏览器.window.onload 当前在 OSX 上覆盖 Chrome、Firefox 和 Safari 中的 body onload
Depends on browser. window.onload currently overwrites body onload in Chrome, Firefox and Safari on OSX
您可以将您的功能添加到加载中:
You can ADD your function to the onload:
window.onload = function() {
alert('window.onload')
}
if (window.addEventListener) {
window.addEventListener('load', function() {
alert('addEventListener')
}, false);
} else if (window.attachEvent) { // IE < 9
window.attachEvent('onload', function() {
alert('attachEvent')
});
}
<body onload="alert('body onload')">
</body>
AND/OR 替换
var bodyOnload = document.body.onload;
window.onload = function() {
alert('window.onload')
bodyOnload()
}
if (window.addEventListener) {
window.addEventListener('load', function() {
alert('addEventListener')
}, false);
} else if (window.attachEvent) { // IE < 9
window.attachEvent('onload', function() {
alert('attachEvent')
});
}
<body onload="alert('body onload')">
</body>
这篇关于将 HTML <body>onLoad 事件会覆盖 javascript 窗口的 onload 事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!