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

Is there a reason why the alert says undefined is loaded?function test(object) {var id = object.id;aler

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745162610a4614457.html

相关推荐

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

    Is there a reason why the alert says undefined is loaded?function test(object) {var id = object.id;aler

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信