数组的索引默认为最后一次迭代

时间:2014-09-02 21:58:49

标签: javascript html5 dynamic-arrays

我定义了一个数组,并将其附加到字符串字段以动态编写HTML TR。我已经命名了一系列与数组中的字符串值相同的JPEG,这样我就可以动态地打印String名称及其相关图像。我的问题是我想在图像中添加一个onclick事件,并传递一个javascript函数,该函数与为表行打印的名称相同。图像和字符串正确迭代,但传递给每个表行的javascript函数的值是默认为最后一个数组项?我尝试了多个场景,并且不明白为什么当用于选择正确的JPEG文件并打印出正确的名称时,同样的storyWords [index]不起作用。

<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>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

稍微重写了一下你的函数并创建了一个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>

我稍微调整了行,列等的创建/追加,而不是将包含table-closing-tag的整行写为一个变量。只是一个建议,因为我更习惯这样写。希望这对你有用,虽然它是一种不同的方法:)