gpt4 book ai didi

javascript - 如何将数据添加到数据表中

转载 作者:行者123 更新时间:2023-12-03 11:00:37 24 4
gpt4 key购买 nike

让我们首先定义我所拥有的。我有一个远程 JSON API,我调用它来获取一些数据。然后,我对数据运行一些简单的函数,最终得到一行数据。这行数据分为三个变量。日期、姓名和消息(想象一个 IRC 聊天室)。我希望在 data table 中显示此数据为了使其可搜索,但是,我在向数据表添加行时遇到问题。目前,我的 HTML 看起来类似于:

<table id="table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Name</th>
<th>Message</th>
</tr>
</thead>

<tfoot>
<tr>
<th>Date</th>
<th>Name</th>
<th>Message</th>
</tr>
</tfoot>
</table>

我的 JS 看起来像:

    var text = document.getElementById('text'); //Text Div
var nameguest = data.items[i].from; //Guests
var nameuser = data.items[i].from.name; //Users
var message = data.items[i].message; //Messages
changeDate(data.items[i].date); //Date
var table = document.getElementById("table"); //Table Div

var row = table.insertRow(i);
row.insertCell(0).innerHTML = datehuman;
if (typeof nameguest == "object") {
row.insertCell(1).innerHTML = nameuser;
} else {
row.insertCell(1).innerHTML = nameguest;
}
row.insertCell(2).innerHTML = message;
}
}

是否有一些与数据表的 insertCell(0).innerHTML 类似的代码?

最佳答案

在表格的 html 中添加额外的“tbody”标记。您可以使用以下函数在表中插入条目。

function insertEntry (tableId, date, name, message) {

var table = document.getElementById(tableId),
tbody = table.getElementsByTagName("tbody")[0],
tr = document.createElement("tr"),
newDateEntry = document.createElement("td"),
newNameEntry = document.createElement("td"),
newMessageEntry = document.createElement("td");

newDateEntry.innerHTML = date;
newNameEntry.innerHTML = name;
newMessageEntry.innerHTML = message;

tr.appendChild(newDateEntry);
tr.appendChild(newNameEntry);
tr.appendChild(newMessageEntry);

tbody.appendChild(tr);
}

您的 HTML 可能如下所示:

<table id="table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Name</th>
<th>Message</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>Date</th>
<th>Name</th>
<th>Message</th>
</tr>
</tfoot>
</table>

对该函数的示例调用如下所示:

insertEntry("table", "1/1/15", "Ayanonly1", "Hellow World");

关于javascript - 如何将数据添加到数据表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28109871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com