Jump to content

Global Array


nicolet
 Share

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...