开发者

Mystery code: +i+ and +x+

开发者 https://www.devze.com 2023-03-02 17:29 出处:网络
In the following code: for (i=0; i<itemsinlist.length; i++) { var rating = document.createElement(\'div\');

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+");");
        ratin开发者_运维问答g.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?


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.


It's putting together this string:

"ratingsSet(0,1);"

The value 0 is in the variable i, and the value 1 is in the variable x. If we add some spaces, it might be more clear:

 "ratingsSet(" + i + "," + x + ");"


As far as I can tell it increments i and x and sets attribute on click for element that is:

"ratingsSet("+i+","+x+");"

Then after click ratingsSet("+i+","+x+"); with params is executed.

Weird way of doing it.


You can have more readable code:

star.onclick = function() {
   ratingsSet(i, x);
};

Setting event handler as attribute breaks in older browsers plus not very elegant.


JavaScript allows you to concatenate strings and integers (and, AFAIK, the string representation of any object) with the plus operator. The resulting HTML (with its embedded JavaScript!) is just that: instantiations of calls to ratingsSet().


"+" is a infix operator that concatenate two strings.

Example : "mor"+"ning" will give the string "morning".

So it simply print the value of i or x to the HTML.


I have the same question, now i know i have made a funny mistake. You must read this statement in a wrong way like me. This second argument need a string, so "ratingsSet("+i+","+x+");" means

"ratingsSet("+
i
+","+
x
+"):"

so this argument will become a string. There are no +x+
:)

0

精彩评论

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

关注公众号