How to Use OnLoad in JavaScript

Source: Internet
Author: User

In the development of previous projects, I encountered several onload usage situations.

1. It can be executed in the Body.
<Body onload = "alert (123)"> </body>
2. Define to useCopy codeThe Code is as follows: <script type = "text/javascript">
Function test (){
Var aa = "hey, you are a pig ";
Alert (aa );
}
Window. onload = test;
</Script>

Annotation: Here window. onload = test; do not add () to the end of test because this is the method for triggering event Association.
If you add (), the execution of this method is immediately triggered (this may not be our intention)
3. Use anonymous Functions
<Script> window. onload = function () {alert (321) ;}</script>
4. How do I write multiple onload events in JS?
<1> <body onload = "aa (); bb (); cc ()"> separate them with semicolons.
<2>
Window. attachEvent ("onload", function () {alert ('A ')});
Window. attachEvent ("onload", function () {alert ('B ')});
Window. attachEvent ("onload", function () {alert ('C ')});
Annotation: Use attachEvent to register an event before the event registration is executed first.
In the above example, c B A is displayed.
Another point: This method can only be used in IE (window. attachEvent)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.