是否存在警报提示未定义加载的原因?
function test(object) {
var id = object.id;
alert(id + " is loaded");
}
<body id="test" onload="test(this);">
<h1>Hello World!</h1>
</body>
答案 0 :(得分:1)
onload函数中的“ this”将引用窗口对象,而不是body元素本身。在您的onload函数中,您需要执行getElementById('test')来获取主体的ID。
答案 1 :(得分:1)
在JavaScript中,正文this
事件上的onload
引用了window
而不是body
。但是,图像元素上的onload
(和iframe
)是指元素本身。为了解决这个问题,我将您的代码更改为:
test(document.body)
onload
JavaScript工作方式的证明:
<!DOCTYPE html>
<html>
<head>
<script>
function test(object) {
console.log("" + object);
}
</script>
</head>
<body id="test" onload="test(this)">
<img src="https://www.google.org/assets/static/images/logo_googledotorg-171e7482e5523603fc0eed236dd772d8.svg" onload="test(this)" />
<h1>Hello World!</h1>
</body>
</html>
答案 2 :(得分:0)
相对于document.body.onload,我更喜欢window.onload,因为它不那么引人注目。但是,两者是相同的。
function test(object) {
var id = object.id;
alert(id + " is loaded");
}
window.onload = function(){ test(document.body); }
<body id="test">
<h1>Hello World!</h1>
</body>
我将onload事件移到了JavaScript。