javascript - 使用 JavaScript 移动 HTML 表格中的项目

标签 javascript html firebase html-table

我正在创建一个堆栈类型的表,因此我希望每个数据项向下移动一行,并将新数据添加到顶部。

JavaScript

for (i = 1; i < 10; i++) {
        for (x = 0; x < 5; x++) {
            var start[] = document.getElementById("coinhistory").rows[i].cells;
            var destination = document.getElementById("coinhistory").rows[i++].cells;
            destination[x].innerHTML = document.getElementById("coinhistory").rows[i].cells;
        }
}

HTML

<table id="coinhistory">
    <tr>
        <th>Game Number</th>
        <th>Outcome</th>
        <th>Choice</th>
        <th>Balance Change</th>
        <th>Generated Number</th>
    </tr>
    <tr>
        <td>example1</td>
        <td>example1</td>
        <td>example1</td>
        <td>example1</td>
        <td>example1</td>
    <tr> //repeated for 10

这就是我到目前为止所拥有的,我希望每个项目在其自己的行中向下移动一次。如果您想要更多代码或其他任何内容,请说。谢谢。

enter image description here

最佳答案

您可以使用insertRow(position)在指定位置插入行,然后将单元格添加到您创建的行中。以下是在第一个位置添加行的示例:

var addRowToTop = (arr) => {
  let table = document.getElementById("coinhistory");
  let row = table.insertRow(1); // insert a new row right under the table headers
  let cells = [];
  for (let i = 0; i < 5; i++) {
    let temp = row.insertCell(i);
    temp.innerHTML = arr[i];
  }
}

addRowToTop(["first", "second", "third", "fourth", "fifth"])
addRowToTop(["this", "one", "above", "last", "one"])
<table id="coinhistory">
  <tr>
    <th>Game Number</th>
    <th>Outcome</th>
    <th>Choice</th>
    <th>Balance Change</th>
    <th>Generated Number</th>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <tr>
</table>

关于javascript - 使用 JavaScript 移动 HTML 表格中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846579/

相关文章:

java - 如何在Firebase数据库Android上获取具有相似子节点的所有父节点?

firebase - 为什么有时imageUrl被保存在Cloud Firestore数据库中而有时却不保存

javascript - 如何禁用div中的超链接

HTML CSS : Best way to Create Search Bar with Magnify Button

ios - Firebase Facebook OAuth在iOS设备上返回null

javascript - Mousedown 事件抑制 focusout 事件?

javascript - HTML 图像的相对路径。在 Github 页面上找不到 404

Javascript-将多个条件合并为1

javascript - 在元素列表中搜索给定字符串

javascript - 检查字符串中字符的 ASCII 码值是否大于或小于前一个字符的 ASCII 码值 - JavaScript