Sometimes, in JavaScript, even if you set the ID may appear document.getElementById () can not get the situation, and then you start to think that the document is wrong, and so on, in fact, it is not your code case has a problem, The main thing is that you haven't figured out exactly where the difference is between what's written directly in <script></script> and what's written in Window.onload=function () {}.
For example, the following is a very simple code, in the Web page in addition to an ID of a, and then wrote the AAAA layer of the div there is no other things, in the head there is a section of the "very standard" script, the <script></script> will be able to , with <script type= "Text/javascript" language= "JavaScript" ></script> there is no difference at all, lest some people think very normative flow of discipline, It is for this reason that it leads to the following series of questions.
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
This script first obtains a layer, and then obtains the content of a layer after window.onload, and estimates that many people think that the first line of codeAlert (document.getElementById ("a"));
Would pop up something like [object:html objectelement]? I think so before, but the actual results are as follows:
Hey? Why is the first alert going to pop empty? This is because HTML at the time of loading, is a line of compilation, dynamic compilation, it is not like the C language, a one-time compilation of the entire program, and then to you to run. This is the difference between the so-called dynamic compilation domain and the static compilation domain. As a result, it can be explained why JavaScript reads that the error will automatically stop executing, and the "javascript" variable conflict that I have mentioned earlier is a problem that can be compiled (click to open link).
Get back to the point. When the page reads the first alert script, there is no layer with ID A at all in the page div! So it's normal to not get it.
There are two workarounds, one is to use Window.onload=function () {}, which requires that the script must be read on all Web pages before it can be run, and the second is to put the script directly at the bottom
Of course, by this example, you also have to be clear, if you introduce JavaScript in the head, like <script src= "Js/jquery-1.11.1.js" ></script> the like, note that If JavaScript is introduced in JavaScript that will be loaded at the beginning of the page, write scripts must be written to Window.onload=function () {}
"JavaScript" appears even if you set the ID and can not get to the probable cause with window.onload