Error creating Javascript Img table

Work on my project for the class, and I ran into a problem. I debugged this problem, but I'm not sure why this is happening. It seems that the problem is limiting the img display for the entire time the table is created. i.e

<tr><td>img</td><td>img2</td></tr> <tr><td></td><td>img2</td><td>img</td></tr> 

Removes the first img and adds it to the created cell. Sorry if I don't make any sense, I will give a code snippet.

 var ImgSrcB = document.createElement("img"); ImgSrcB.src = "Black.png"; var ImgSrcW = document.createElement("img"); ImgSrcW.src = "White.png"; var body = document.body, tbl = document.createElement('table'); tbl.style.width = 50*8; tbl.style.height = 50*8; for (var i = 0; i < 8;i++) { var tr = tbl.insertRow(); var td; for (var j = 0; j < 8; j++) { if (i%2 == 0) { if (j % 2 == 0) { td = tr.insertCell(); td.appendChild(ImgSrcB); } else if (j %2 == 1) { td = tr.insertCell(); td.appendChild(ImgSrcW); } } else if (i % 2 == 1) { if (j % 2 == 0) { td = tr.insertCell(); td.appendChild(ImgSrcW); } else if ( j % 2 == 1 ) { td = tr.insertCell(); td.appendChild(ImgSrcB); } } console.log(i, j); //Debug Purposes } } body.appendChild(tbl); 

Any idea why this is happening? Do I have a misunderstanding in appendChild?

+5
source share
1 answer

You create one image and then add it everywhere. When you add a DOM node that is already found in the DOM, it will be deleted from the old location and added to a new location, therefore, you will see the same instance of the image moving (more precisely, you just see it in its last place according to the loop).

You need to create a new instance of the correct image for each iteration of the loop and add it.

+4
source

All Articles