Reputation: 867
I have a script in JavaScript which is called several times in a html page. I want to know how it's possible to assign values to a variable only the first call of the script.
var processingYear = 0;
var recupMonth = 0;
var recupYear = 0;
if(processingMonth == startMonth && processingYear == startYear && recupMonth == 0 && recupYear == 0){
recupMonth = startMonth;
recupYear = startYear;
}
Upvotes: 4
Views: 80
Reputation: 929
window.count ? count="defined" : count="undefined";
if(count=="undefined"){
var processingYear = 0;
var recupMonth = 0;
var recupYear = 0;
}
Just another way to do !
Upvotes: 0
Reputation: 27833
If i understand correctly you want to include the same script multiple times in the same HTML page. To prevent the script from overwriting your initializations, you can simply check if the variables have values before redefining them:
Instead of:
var x = 2;
Do:
var x = (x !== undefined) ? x : 2;
A shorter version would be var x = x || 2;
, but that can backfire if your x variable holds a value that is evaluated to false (for example 0) after the script is executed.
Upvotes: 3