Document.getelementbyid gets the solution that the control object is empty

  • 2020-03-29 23:52:45
  • OfStack

1. Here is a simple example of a page that displays a piece of information when it loads


<%@ 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 loads </h1>
  </body>
</html>

After execution, it is indeed "output information before page load".
2. The following example shows that document.getelementbyid is null.
My plan is: when the page loads, in < Body> < / body> "Text box displays data processed by the background, such as the string" hello, my friend! . But here by reading through document.getelementbyid the object is empty.
Because the onLoad method is on the page < Body> < / body> Before loading, id="mes" corresponds to the text box of the text box, which has not been loaded.


<%@ 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. Solutions
When an Html page loads, it loads. Html> < / html> All the data in. First load < Head> , reload < Body> .
So we can do it in < / body> After that, in < / html> I just wrote javascript. The program is executed sequentially, until the corresponding javascript call is executed. Instead of using the onLoad method.
The 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 to perform javascript code  -->
    <script language="javascript">
          function showMessage()
          {
              var t=document.getElementById("mes");
              t.value="hello, my friend!"
          }
          showMessage();    //Call the method, update the text box
      </script>
</html>


Related articles: