使用 Javascript 方法 append 和 appendChild 将行和单元格插入 HTML table

Using Javascript methods append and appendChild to insert row and cells into a HTML table

没错。伙计们,我遇到了一个我一生都无法解决的简单问题。我正在尝试使用 JavaScript 在 Bootstrap table 的末尾插入一个新行(使用来自 AJAX 调用的响应数据)。我正在使用这样一个简单的函数;

                function insertRow(data) {

                    let tbody = document.querySelector('tbody');
                    let spacer = document.createElement('tr');
                    let tr = document.createElement('tr');

                    // append rows to table
                    tbody.appendChild(spacer);
                    tbody.appendChild(tr);

                    // apply styles                    
                    tr.className = 'rounded-3 card-body shadow-sm reg-rows';
                    spacer.className = 'spacer';
                    spacer.style.height = '6px';

                    let id_input = document.createElement("input");

                    spacer.appendChild(id_input);
                    id_input.value = `${data.identifier}`;
                    id_input.name = "keys_array[]";
                    id_input.type = "hidden";

                    let cells_array = new Array();

                    // create cells
                    var td_id, td_ba, td_code, td_num;
                    td_id = td_ba = td_code = td_num = document.createElement('td');

                    // append cells to row                    
                    tr.append(td_id, td_ba, td_code, td_num);

                    // add cells to array
                    cells_array.push(td_id, td_ba, td_code, td_num);

                    Array.prototype.slice.call(cells_array)
                        .forEach(function(cell) {
                            cell.className = "p-1 border-0";
                            tr.appendChild(cell);
                        });

                    td_status.classList.add("rounded-end");

                    let div = document.createElement("div");

                    let input = document.createElement("input");
                    input.className = "form-check-input position-static";
                    input.name = "some_action[]";
                    input.type = "checkbox";

                    div.appendChild(input);

                    td_status.appendChild(div);


                    // write text to cells
                    td_id.innerHTML = `${data.id}`;
                    td_ba.innerHTML = `${data.ba}`;
                    td_code.innerHTML = `${data.code}`;
                    td_num.innerHTML = `${data.num}`;
  
                }

问题是当我调用该函数时,只有最后一个单元格(在本例中为 td_num)被插入到新创建的行中,并且它被插入作为第一个。

我试过使用 appendChild 将每个单元格单独附加到新行,但也没有。

我什至尝试更改单元格的创建和附加顺序,但没有奏效。我做错了什么?谢谢

您正在为这一行中的同一个 Element 创建 3 个引用:

td_id = td_ba = td_code = td_num = document.createElement('td');

意思是,这里创建的唯一document.createElement('td')可以用td_idtd_batd_code来调用。您没有在此处创建 3 个 td,只有一个具有 3 个引用。

如果要创建 3 个元素,则需要为每个变量创建它们

[ td_id, td_ba, td_code ].map(myVarRef => myVarRef = document.createElement('td'))
<html>

<head>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous">
  </script>
  <script>
    function insertRow() {

      let data = [{
        cell1: "3",
        cell2: "Item 3",
        cell3: ""
      }, {
        cell1: "4",
        cell2: "Item 4",
        cell3: ""
      }];

      // I choose table body over table by adding an ID specifically
      let table_body = document.getElementById("tbody_id");
      for (let i = 0; i < data.length; i++) {
        // Create an empty <tr> element and add it to the last position of the table:
        let row = table_body.insertRow(-1);

        // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
        let cell1 = row.insertCell(0);
        let cell2 = row.insertCell(1);
        let cell3 = row.insertCell(2);

        // Add some text to the new cells:
        cell1.innerHTML = data[i].cell1;
        cell2.innerHTML = data[i].cell2;
        cell3.innerHTML = data[i].cell3;

      }
    }
  </script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-sm-3">
        <button type="button" onclick="insertRow()" class="btn btn-primary">Click Me</button>
      </div>
    </div>

    <div class="row">
      <div class="col-sm">
        <table data-toggle="table" id="test-table">
          <thead>
            <tr>
              <th>Item ID</th>
              <th>Item Name</th>
              <th>Item Price</th>
            </tr>
          </thead>
          <tbody id="tbody_id">
            <tr>
              <td>1</td>
              <td>Item 1</td>
              <td></td>
            </tr>
            <tr>
              <td>2</td>
              <td>Item 2</td>
              <td></td>
            </tr>
          </tbody>
        </table>

      </div>
    </div>
  </div>
</body>    
</html>

我创建了一个示例,您可以直接 运行,希望这对您有所帮助。我在代码本身添加了注释以便更好地理解,同时插入行你可以给 -1 附加到 table 正文的底部。