I am new to JavaScript.
I understand that a global variable should be visible all over the page, but this doesn't seem to be the case.
In the HTML head I have <script>
tags where I defined a global variable, but this variable does not exist in the <script>
tags in the HTML body. I checked with alert(varname==null)
.
I do not understand this.
The reason the code is not placed together is for the document to finish 'loading', so that the script will be able to access the it is working on. Is there a standard way to do this?
It is ridiculous that my code cannot work in either places - can't work in the because the <div>
isn't loaded yet and can't work in the <body>
because the global variable isn't visible!
EDIT
I defined my global variables using "var varname;" without giving them a value, apparently that didn't count as defining them. Changed it to var "varname = [];" and now it works. Initiating to null didn't work either.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…