I came across a sample HTML/Javascript code
<!DOCTYPE html>
<html>
<body>
<div id='showCD'></div><br>
<input type="button" onclick="previous()" value="<<">
<input type="button" onclick="next()" value=">>">
<script>
var i = 0;
displayCD(i);
function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
function next() {
if (i < x.length-1) { // why does x here not raise an error? it came from nowhere.
i++;
displayCD(i);
}
}
</script>
</body>
</html>
The only question I had is why is it okay to use x in function next(){} when it is defined in myFunction(xml, i){} ?
When the page first loads, displayCD(0) is executed. So the only theory I could come up with is x stays in memory because it is a global variable (it does not use var.)
Please correct me if I am wrong.
Thanks
x = xmlDoc.getElementsByTagName("CD");) - but where is next() used?next()even called? It's defined but not used so that may be why it doesn't give an error.xdoesn't "remember" how it got its value. Simplified example: ifais local,bis global andvar a = 1; b = a;then the value ofbwill always be 1 (unless specifically changed) even ifadoesn't exist anymore.