1. The following is a simple example. A piece of information is displayed during page loading.
Copy codeThe Code is as follows:
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Script language = "javascript">
Alert ("hello !!! ");
</Script>
</Head>
<Body onLoad = "showMessage ()">
<H1> some information is output before the page is loaded </Body>
</Html>
After execution, it is true that "information is output before page loading ".
2. The following example shows that document. getElementById is null.
My plan is to display the data processed by the background in the <body> </body> text box during page loading, for example, the string "hello, my friend! ". However, the object read through document. getElementById is null.
Because the onLoad method is executed before the page <body> </body> is loaded, the text box corresponding to the id = "mes" text box is not loaded yet.
Copy codeThe Code is as follows:
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Script language = "javascript">
Var t = document. getElementById ("mes ");
T. value = "hello, my friend! "
</Script>
</Head>
<Body onLoad = "showMessage ()">
The message is: <input type = "text" id = "mes">
</Body>
</Html>
3. Solution
When an Html webpage is loaded, the data in Therefore, we can write javascript before </body>. The program is executed in sequence and executed to the corresponding javascript call. The onLoad method is not used.
The Code is as follows:
Copy codeThe Code is as follows:
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Body>
The message is: <input type = "text" id = "mes">
</Body>
<! -- Continue executing javascript code -->
<Script language = "javascript">
Function showMessage ()
{
Var t = document. getElementById ("mes ");
T. value = "hello, my friend! "
}
ShowMessage (); // call a method to update the text box
</Script>
</Html>