Javascript function in html body, wont work

2019-10-03 07:55发布

In my document I have an onLoad function given like here in this example:

<body onLoad="display()">

In addition I added a function at the end of the document which changes some CSS properties:

<script>
window.onload = foo(), bar();
</script> 

Somehow the whole thing doesn't work! I tried to add all functions at the end of the document but I don't get it, somehow they don't trigger!

2条回答
闹够了就滚
2楼-- · 2019-10-03 08:36

That will invoke the functions, but it doesn't assign anything useful to window.onload unless your last function happens to return a function.

You need to assign a function to window.onload that will invoke your functions when the window is ready.

window.onload = function() {
    foo();
    bar();
};

Plus, since you're putting the script at the bottom, you probably don't need the window.onload.

    <script>
        foo(); bar();
    </script>
</body>

You should also be aware that assigning directly to window.onload will overwrite the script assigned in the <body onLoad=...>, so you shouldn't do both. Currently, the return value of bar(); is wiping out the function that invokes display();.

Getting rid of the window.onload assignment will fix that.

查看更多
我只想做你的唯一
3楼-- · 2019-10-03 08:36

In the first case, I don't see a reason why it shouldn't work, as long as display() is defined function with no errors.

In the second case, when assigning event handlers via DOM, you need to pass either a function reference (i.e. instead of foo() just foo) or wrap it in an anonymous function like so:

window.onload = function() {
  foo();
}
查看更多
登录 后发表回答