开发者

How to pass a global variable to multiple functions in multiple files

<script> 
var word = new Array(); word[1] = 'new'; word[2] = 'old';
</script> 

<script src="javascript/validator.js" type="text/javascript"></script>

And, in the validator.js we have:

function validate(number){ 
  alert(word[number]);
}

How to catch the variable value? I always get an error saying the variable do开发者_JAVA百科esn't exist.


You almost got it.

This is the way I managed my multi-language message:

First I defined the array at the top of the page; as close as possible to the HEAD tag

<script type="text/javascript">
    var resx = {};
</script>

Then, I fill the array with the values, using whatever method you use to get it from the database. In this example I use ASP.NET MVC.

<script type="text/javascript"> 
     resx["word1"] = '@Model.word1';    
     resx["word2"] = '@Model.word2';    
     //or you can fill it directly
     resx["word3"] = 'Name';
     resx["word4"] = 'Nombre';
</script>
<script src="javascript/validator.js" type="text/javascript"></script>

Then you use the way you want in the js file:

validate(“word2”);
function validate(value){ 
   alert(resx[value]);
}

//Or:
alert(resx[“word3”]);

I hope this help.


First, it's probably not a good idea to be referencing globals across files. It can be confusing for other team members or maintainers to track them down. I would suggest always passing all necessary values to a function. This documents exactly what the function requires. Try this,

<script src="javascript/validator.js" type="text/javascript"></script>
<script type="text/javascript"> 
var word = new Array('new', 'old');
validate(word, 0);
</script>

And in validator.js:

function validate(w, n){ 
    alert(w[n]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜