Reputation: 67
Js file inside I have a function with a particular algorithm.
For reading xml file and transform the data to variable name wordData.
Inside the function has the following line of code:
var wordData = xhr.responseXML.getElementsByTagName (Node1);
I can not set the variable "wordData as a global" outside the function or global Inside the function
function language() {
lang = "heb";
if (lang == "heb") {
thisWord = wordArrayHeb[indeXML];
}
else {
thisWord = wordArrayEng[indeXML];
}
alert("language thisWord:=" + thisWord);
}
function setWord() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var wordData = xhr.responseXML.getElementsByTagName(Node1);
XMLength = wordData.length;
for (i = 0; i < XMLength; i++) {
wordArrayHeb[i] = wordData[i].getElementsByTagName(Node2)[0].firstChild.nodeValue;
wordArrayEng[i] = wordData[i].getElementsByTagName(Node3)[0].firstChild.nodeValue;
}
language();
}
}
}
}
the variable thisWord is effected from varible wordData which is not global. Outside the functions, varible thisWord is empty inside the function is ok and it has a value.
Would love help. Thank you!
Upvotes: 0
Views: 1936
Reputation: 11588
i think setting it as a global var is not the best choice, if you wish to access wordData inside the function language, you should pass it as a parameter like so:
language(wordData);
and in declaring function language(), just make it so it accepts the parameter:
function language(wordData) {
...
}
Upvotes: 0
Reputation: 471
You can create a global var anywhere in JS by using the window object:
window['wordData'] = xhr.responseXML.getElementsByTagName(Node1);
or
window.wordData = xhr.responseXML.getElementsByTagName(Node1);
Then wordData can be accessed globally. This may not be the best solution for your problem, consider using function arguments and return values instead.
Upvotes: 2
Reputation: 7631
Simply declare
var wordData;
outside the function and change your line to:
wordData = xhr.responseXML.getElementsByTagName (Node1);
Hence removing the var declaration.
Upvotes: 2