How Can I Define Variables In A JavaScript File Within An Html File In Which The JavaScript Is Used?
Solution 1:
You should define your local variables before including the script.
<script>
// local variables
var firstname = "John", lastname = "Doe";
</script>
<script src="hellohello.js"></script>
In the js file, we need to make sure our local variables exists, if it doesn't we can define default variables or stop the script.
// Check if the variable already exists
// If it doesn't we'll give it a default variable
if(typeof(firstname)==='undefined') firstname = "Guest";
if(typeof(lastname)==='undefined') lastname = "";
alert("Hello "+ firstname +" "+ lastname);
// Or just do something else
if(typeof(firstname)!=='undefined' && typeof(lastname)!=='undefined') {
// Do something
} else {
// Do nothing
}
Demo 1: http://bycreativeminds.com/playground/vanilla/js-demo-110.html
Demo 2: http://bycreativeminds.com/playground/vanilla/js-demo-111.html
Solution 2:
I don't know if this is better then hutchbat's or not, but it is a different way.
What I did was break up buttons.js into two files: buttons_init.js and buttons.js
buttons_init.js includes all the intialization, but not the code that uses it
var text = new Array[100]
var num = 0
var NAME = PROJECT
var LAST = 100
var LAST1 = 99
So in your HTML, you do this (preferably at the buttom unless you need it to run early):
<script type="text/javascript" src = "../buttons_init.js">
<script>
// overwrite any variables you need to change
num = 5
LAST = 200
LAST1 = LAST-1
</script>
<script src = "../buttons.js>
The advantage of this is that you don't have to remember to check to see a variable is undefined in your buttons_init.js. The disadvantage is that you have two files to include (which slows down the load slightly, although not as much as it used to) and you have to remember to put default variables you want people to override in the _init file (which has the side affect of documenting it). Some people will prefer one way, some will prefer the other. I'm just presenting it as an alternative.
A completely different way would be to send an "options" structure into the Next and Prev functions (merging them with default values inside the functions), or make them into a class (or jQuery plugin), but that seems overkill for such a simple example.
Post a Comment for "How Can I Define Variables In A JavaScript File Within An Html File In Which The JavaScript Is Used?"