Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) {
table += "<tr onclick='displayCD(" + i + ")'><td>";
table += x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
table += "</td><td>";
table += x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
function displayCD(i) {
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;
}
</script>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<!DOCTYPE html>
<html>
<body>
<p>Click on a CD to display album information.</p>
<p id='showCD'></p>
<table id="demo"></table>
</body>
</html>
I don't understand what + i +
means inside that function. I've never seen anything like that before.
</div>
i refers to index there in order to pass dynamic input for each table row function displayCD will pass dynamic index in each table row . For example first row it will be displayCD('0') , second row it will be displayCD('1') and this will continue until length of the array.
Inside this loop, i
is the iterator, so it starts at 0
and increases by 1
every time the loop repeats until i
is less than than the length of x
, at which time the loop will stop.
for (i = 0; i <x.length; i++) {
table += "<tr onclick='displayCD(" + i + ")'><td>";
table += x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
table += "</td><td>";
table += x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
table += "</td></tr>";
}
The line table += "<tr onclick='displayCD(" + i + ")'><td>";
appends some HTML to the table. The " + i + "
part inserts the iterator into the loop, so if the loop had been processed twice, i
would be equal to 1
and the line table += "<tr onclick='displayCD(" + i + ")'><td>";
would become table += "<tr onclick='displayCD(1)'><td>";
.
+
adds strings (or numbers depending on the context) together, so "hello " + "world" + "!"
essentially means "hello world!"
.
You can also add strings to variables. For example, if i
is equal to 7
and you write "hello " + i + "!"
, that essentially means "hello 7!"
. This is known as concatenation.
In your case, you are concatenating i
into a function call.
It's a concatenation, displayCD(" + i + ") will rendering displayCD(1), displayCD(2)... i refers to the variable incremented in the loop.