Search code examples
javascripthtmldynamic-arrays

index of array is defaulting to last iteration


I have an array defined and appending it to a string field to dynamically write a HTML TR. I have named a series of JPEGs with the same name as the string value in the array so that I can dynamically print the String name and its associated image. My problem is that I want to add an onclick event to the image and pass a javascript function the same name that is printed for the table row. The images and string iterate properly but the value passed to the javascript function for each table row is defaulting to the last array item? I tried multiple scenarios and don't understand why the same storyWords[index] isn't working when it used to choose the correct JPEG file and print out the correct name.

<script type="text/javascript">
var storyWords = "";
var index;
var strWord ="";

function doStuff(word){
alert(word);     

};
$(document).ready(function(){


var storyId = localStorage.getItem("StoryId");
var strHTML = "<table>";
if (storyId == "1"){
    storyWords = ["Ant", "Bananas", "Bottle", "Car", "Castle"];
}
else if (storyId == "2"){
    storyWords = ["Dragons", "Football", "Hollow", "Hospital", "Island"];
}
else if (storyId == "3"){
    storyWords = ["Log", "Party", "Mountain", "Poles", "Princess"];
}
 else{
    storyWords = ["Trophy"];
}


for (index = 0; index < storyWords.length; index++){
    strWord = storyWords[index];
    strHTML += "<tr><td><img src=img/Words/" + storyWords[index] + ".jpg    onclick=doStuff("+ storyWords[index] +");>&nbsp;&nbsp;" + storyWords[index] + "</td></tr>";
}

$('#wordText').html(strHTML + "</table>"); 

 });
</script>

Thanks for any help!


Solution

  • Just rewrote your function a bit and created a Fiddle

    $(document).ready(function () {
      function doStuff(word) {
        alert(word);
      }
      var storyId = 3;  // just set static storyId 3 as example
      var table = $('<table>');
      if (storyId == "1") {
        storyWords = ["Ant", "Bananas", "Bottle", "Car", "Castle"];
      }
      else if (storyId == "2") {
        storyWords = ["Dragons", "Football", "Hollow", "Hospital", "Island"];
      }
      else if (storyId == "3") {
        storyWords = ["Log", "Party", "Mountain", "Poles", "Princess"];
      }
      else {
        storyWords = ["Trophy"];
      }
    
    
     for (index = 0; index < storyWords.length; index++) {
    
        (function (story) {
            strImg = "";
            var tr = $('<tr>');
            var td = $('<td>');
            var img = $('<img>');
            img.attr('src', 'img/Words/' + story + '.jpg');
            img.click(function () {
                doStuff(story);
            })
            img.appendTo(td);
            td.append("  " + story);
            td.appendTo(tr);
            tr.appendTo(table);
        })(storyWords[index]);
       }
      $("#wordText").append(table);
    });
    

    HTML:

    <div id="wordText"></div>
    

    I adjusted the creating / appending of the rows, columns, etc a bit instead of writing the whole row including the table-closing-tag as one variable. Just a suggestion as I'm more used to write it like that. Hope this is of any use for you though it's kind of a different approach :)