Skip to content Skip to sidebar Skip to footer

Why Can't I Get My Images To Appear In Table Cells/nodes.. Maybe I Can Get Some Closure?

I want to add a new image in each cell of the new table and give it the same source as the old table, and then make it clickable. Firstly, I did this: function showData() { if (l

Solution 1:

In your code you have:

var newImages = newTable.getElementsByTagName('img');

for (var i = 0; i < newImages.length; i += 1) {
  var picSource = newImages[i]['src'];
  console.log(picSource);
}

At the end of this, picSource has the value of the last image's src attribute. Then there is:

functionaddNewImage(newNumCols) {
  var newImg = newImage();
  newImg.src = picSource;
  col.appendChild(newImg);
  newImg.onclick = function() {
    alert("WOW");
  };
}

A value is passed to newNumCols but not used in the function. The value of picSource comes from the outer execution context and is not changed, so it's still the last image src from the previous for loop.

for(r =0; r < newNumRows; r++){
  row = newTable.insertRow(-1);

  for(c=0; c< newNumCols; c++){
    col = row.insertCell(-1);
    addNewImage(newNumCols);
  }}

This loop just keeps calling addNewImage with a single parameter that isn't used in the function, so you get the same image over and over.

For the record, the addNewImage function does have a closure to picSource, but it also has a closure to all the variables of the outer execution contexts. This isn't the issue, though it perhaps masks the fact that you aren't setting a value for picSource on each call, so you get the left over value from the previous section of code.

You haven't provided any indication of the content of showme, so it's impossible to determine if this approach will work at all.

Note

Where you have:

var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";

IE does not support setting the innerHTML property of table elements, though you can create an entire table as the innerHTML of some other element and set the innerHTML of a cell (tr, th). If you want to use this approach, consider:

var div = document.createElement('div');
div.innerHTML = '<table id="newTable">' + showme + '<\/table>';
var newTable = div.firstChild;

Post a Comment for "Why Can't I Get My Images To Appear In Table Cells/nodes.. Maybe I Can Get Some Closure?"