Nick Nick - 1 month ago 9
Javascript Question

Mystery code: +i+ and +x+

In the following code:

for (i=0; i<itemsinlist.length; i++) {
var rating = document.createElement('div');
itemsinlist[i].appendChild(rating);
rating.className = "rating";
rating.id = "thumbnails" +i;

for (x=0; x<4; x++) {
star = document.createElement('span');
star.innerHTML = "&#9733;";
star.className = "star";
star.setAttribute("onclick", "ratingsSet("+i+","+x+");");
rating.appendChild(star);
} //createratingsstars


I'm struggling to make sense of the second parameter to
star.setAttribute()
, in the line:

star.setAttribute("onclick", "ratingsSet("+i+","+x+");");


Specifically, I'm being thrown off by the
+i+
and
+x+
.

At first I thought these were some kind of variation on the increment operator, but later decided it must be concatenating something, but I can't figure out what/how. The HTML that gets generated by the loop is:

<span class="star" onclick="ratingsSet(0,0);">*</span>
<span class="star" onclick="ratingsSet(0,1);">*</span>
<span class="star" onclick="ratingsSet(0,2);">*</span>
<span class="star" onclick="ratingsSet(0,3);">*</span>


But my reverse-engineering chops are failing me (if I had any to begin with).

Help?

Answer

It's string concatenation. i is the outer loop counter, and x is the inner loop counter. It appears to be iterating a collection and creating 4 spans per item.

Comments