Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
867 views
in Technique[技术] by (71.8m points)

javascript - JS code not working because of bad placement

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you want to run a javascript code on finish loading, a best practice is to make a function that is called in the onload method.

HTML Code

<body onload="changediv('2');">
    <div id="1">11111111111 1111111111111 111111111</div>
    <div id="2">222222c   2222222222222 22222222</div>
    <div id="3">23333333 3 333 3 3 3 3 3 33333 3</div>
    <div id="4">4444 4  4 44444 4 4 4 4444 </div>
</body>

Javascript function

function changediv(id){
    var d = document.getElementById(id);
        d.style.color = "#ccc";
}

here you have an example on JSBIN

http://jsbin.com/ajawic/1/edit

In this way, you ensure that the object exists before use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...