使用javascript数组填充html表 [英] Populate html table with javascript array

查看:127
本文介绍了使用javascript数组填充html表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JavaScript array填充HTML表. 但是,它不起作用,我也不知道为什么,我的"innerHTML"没有得到解释.

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 contains the good value, but when I do this :

document.getElementById("title").innerHTML = title;

它不起作用.

这是我的代码:

var title = "";
var link = "";
var date = "";
var image = "";

function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "my_url");
xhr.onload = function () {
    if (xhr.responseText == 0) {
        alert("Vous n'avez poster aucun post");

    } else {
        var posts_array = JSON.parse(xhr.responseText);

        for (var i = 0; i < posts_array.length; i++)
        {
            title = posts_array[i][0];
            link = posts_array[i][1];
            date = posts_array[i][2];
            image = posts_array[i][3];

        }
    document.getElementById("title").innerHTML = title;
    }
}
xhr.send();
}

这是我的HTML:

<table id="posts">
                <tr>
                    <th id="test">Titre</th>
                    <th>Lien</th>
                    <th>Date</th>
                    <th>Image</th>
                </tr>
                <tr>
                    <td id="title"></td>
                    <td id="link"></td>
                    <td id="date"></td>
                    <td id="image"></td>
                </tr>
            </table>

推荐答案

您要在循环内分配title的值,然后将单个单元格的innerHTML设置为title.假设您的responseText格式正确,则posts表将仅包含数组中的最后一个元素.似乎您需要为posts_array中的每个项目创建一个新的表行,并将其添加到posts表中以获得预期的结果.

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.

例如

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

这篇关于使用javascript数组填充html表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆