开发者

Cannot get declared variables in javascript

Consider a javascript file script.js which contains the code alert(theVar);

Now, i linked the js file to the document like

<script type="text/javascript">
    var theVar= 'a alert';
</script>
<script type="text/javascript" src="script.js"></script> //Contains alert(theVar);

The variable theVar is used and i get a alert. This works fine.

When,

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
 开发者_Python百科    var theVar= 'a alert';
 </script>

is used, i am not getting a alert.

I know the problem is because of the variable, which is declared after loading the js file.

But is there any way to get the variable declared anywhere in the document ?


in script.js do

window.onload = function() { alert ( theVar ) }

Or your favorite library dom ready fn, so it invokes the callback after a certain event instead of immediately.

Though, this really depends on what kind of functionality script.js has, which you have not specified thus far.


The important bit is that code gets executed in the appropriate order. You should delay the call to alert(theVar) until the document gets fully loaded. For instance, you can attach an onload event handler to the window object.

It's also worth noting that calling external *.js files does not affect the way code gets run.


The simple solution:

Move the script.js inclusion to the last row of the body. That way a variable declared at any point in the document can be used.

The technical solution:

Inside script.js, hook on to the window.onload event before doing any evaluating. The result is the same as with the simpler solution, but allows you to keep you script tags in the head (or anywhere for that matter).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜