Suppose I have some html file and it's have some script inside it. Then, I need to use another one script and want to use some variable from previous one. How Can I do it? Example:
<body>
<script>
var a = 1;
</script>
<p id="p"></p>
<script>
document.getElementById("p").innerHTML = a;
</script>
</body>
Its says that "a" is undefined.
-
1It is working fine do you have variable in different JS filesMuhammad Ali– Muhammad Ali2014年07月26日 09:00:47 +00:00Commented Jul 26, 2014 at 9:00
-
2As posted your code works OK. See jsfiddle.net/E6cupAdam– Adam2014年07月26日 09:00:51 +00:00Commented Jul 26, 2014 at 9:00
-
1It works without an error. Keep in mind that order of the script tag matters.Fizer Khan– Fizer Khan2014年07月26日 09:07:34 +00:00Commented Jul 26, 2014 at 9:07
-
@Dima better tell also what was the problem.Mritunjay– Mritunjay2014年07月26日 09:12:45 +00:00Commented Jul 26, 2014 at 9:12
2 Answers 2
Yes, you can do it. Your code works without any error. If you declare a variable inside the script tag directly, it comes under global scope which can be accessible from anywhere. But that script must be included before script which uses the variables.
Better you can define your namespace and use that. Otherwise your global variable most likely clash with other script's variable. It will be painful to debug.
var myNamespace = {};
myNamespace.a = 2;
In other scripts, use it like myNamespace.a.
Comments
Just Put all Script codes inside a Head tag
<head>
<script>
var a = 1;
</script>
<script>
document.getElementById("p").innerHTML = a;
</script>
</head>
<body>
<p id="p"></p>
</body>