最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get id of element from onload - Stack Overflow

programmeradmin0浏览0评论

Is there a reason why the alert says undefined is loaded?

function test(object) {
  var id = object.id;
  alert(id + " is loaded");
}
<body id="test" onload="test(this);">
  <h1>Hello World!</h1>
</body>

Is there a reason why the alert says undefined is loaded?

function test(object) {
  var id = object.id;
  alert(id + " is loaded");
}
<body id="test" onload="test(this);">
  <h1>Hello World!</h1>
</body>

Share Improve this question edited Aug 26, 2018 at 6:15 Ramesh 2,4132 gold badges24 silver badges44 bronze badges asked Aug 26, 2018 at 4:37 zerodramazerodrama 511 silver badge6 bronze badges 3
  • Have you tried put the script before /body ? – A. Meshu Commented Aug 26, 2018 at 4:42
  • Interesting will try – zerodrama Commented Aug 26, 2018 at 4:43
  • This might work with img onerror stackoverflow./questions/4057236/… – zerodrama Commented Aug 26, 2018 at 5:25
Add a ment  | 

3 Answers 3

Reset to default 2

In JavaScript, the this on the onload event on body refers to window instead of body. However, the onload on image elements (and iframe) refers to the element itself. To get around this, I would change your code to:

test(document.body)

Proof of how onload works 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/assets/static/images/logo_googledotorg-171e7482e5523603fc0eed236dd772d8.svg" onload="test(this)" />
<h1>Hello World!</h1>
</body>
</html>

"this" in your onload function will refer to the window object, not to the body element itself. In your onload function, you'll need to do a getElementById('test') to get the body's id.

I prefer window.onload than document.body.onload because it is less obtrusive. But, both however are the same.

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>

I moved the onload event to the JavaScript.

发布评论

评论列表(0)

  1. 暂无评论