Populate html table with javascript array

后端 未结 3 1410
情话喂你
情话喂你 2021-01-21 12:32

I would like to fill an HTML table with a JavaScript array. But, it doesn\'t work and I don\'t know why, my \"innerHTML\" is not interpreted.

My variable co

3条回答
  •  生来不讨喜
    2021-01-21 13:08

    You're assigning the value of title inside your loop and then setting the innerHTML of an individual cell to title. Assuming your responseText is formatted correctly, the posts table will only ever contain the last element in your array. It seems like you need to create a new table row for each item in posts_array and add it to the posts table to get your intended result.

    e.g.

    var t = "";
    for (var i = 0; i < posts_array.length; i++){
          var tr = "";
          tr += ""+posts_array[i][0]+"";
          tr += ""+posts_array[i][1]+"";
          tr += ""+posts_array[i][2]+"";
          tr += ""+posts_array[i][3]+"";
          tr += "";
          t += tr;
    }
    document.getElementById("posts").innerHTML += t;
    

提交回复
热议问题