Jump to content

Global Array


nicolet

Recommended Posts

I have a file,Example.js, containing the line var document.myGlobalVariable = [ 'Patricia', 'Agatha', 'Betty', 'Carla'];My intention is to create a global array accessible to several html pages.Another file, Example.html, contains:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html;charset=ISO-8859-1"><script src="Example.js"></script></head><body>...<script>document.write(document.myGlobalVariable[0]);</script>...</body></html>Firefox developer tools reports "document.myGlobalVariable is not defined".How can I define, in a .js file, an Array that is accessible to several .html files.?

Link to comment
Share on other sites

Try making it a variable instead of a property of document.

Link to comment
Share on other sites

I think it should work as a property of document, I've used it before, but it's not necessary. By making it a variable outside any functions it becomes global on its own.You may not be calling the script correctly. Use this tag:<script type="text/javascript" src="Example.js"></script>

Link to comment
Share on other sites

Since it is an external javascript file, another explanation of this behavior is that the inline script that is attempting to access your variable may be executing before the external file has been loaded by the browser.Try changing your HTML to something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html;charset=ISO-8859-1"><script src="Example.js"></script><script>window.onload = function() { document.getElementById("output").innerHTML = document.myGlobalVariable[0]; }</script></head><body><div id="output"></div></body></html>

Link to comment
Share on other sites

Hearty thanks to Synook, Indolme, and jesh for their prompt help! My final working versin:File Example.js:var myGlobalVariable = [ 'Patricia', 'Agatha', 'Betty', 'Carla'];File Example.html:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html;charset=ISO-8859-1"><script type="text/javascript" src="Example.js"></script></head><body><h1>Global Variable</h1><script>document.write(myGlobalVariable[0]);</script></body></html>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...