css 当我添加一行时,它无法识别添加的行,而只是添加原始行,而不是包含添加的行

mspsb9vt  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(130)

我想创建一个表,在添加行时也会添加列,但实际情况是,当我添加行时,添加列时只计算原始行

const table = document.getElementById("myTable");
const addColumnButton = document.querySelector(".addColumn");
const removeColumnButton = document.querySelector(".removeColumn");
const addRowButton = document.querySelector(".addRow");
const removeRowButton = document.querySelector(".removeRow");

addColumnButton.addEventListener("click", function() {
  // Get all rows in the table
  const rows = table.rows;

  // Insert new cells in each row
  for (let i = 0; i < rows.length; i++) {
    const cell = rows[i].insertCell(-1);
    cell.innerHTML = `Column ${rows[i].cells.length}`;
  }
});

// 

removeColumnButton.addEventListener("click", function() {
  // Get all rows in the table
  const rows = table.rows;

  // Remove the last cell in each row
  for (let i = 0; i < rows.length; i++) {
    rows[i].deleteCell(-1);
  }
});

addRowButton.addEventListener("click", function() {
  // Create a new row element
  const newRow = table.insertRow();

  // Insert new cells
  const cell1 = newRow.insertCell(0);
  const cell2 = newRow.insertCell(1);
  const cell3 = newRow.insertCell(2);

  // Add content to the cells
  cell1.innerHTML = "New Row, Column 1";
  cell2.innerHTML = "New Row, Column 2";
  cell3.innerHTML = "New Row, Column 3";
});

removeRowButton.addEventListener("click", function() {
  table.deleteRow(-1);
});
table,
th,
td {
  border: 1px solid black;
}

.tdaction {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Table</title>
  <script src="table.js" defer></script>
  <link rel="stylesheet" href="table.css">
</head>

<body>
  <button class="addColumn">Add Column</button>
  <button class="removeColumn">Remove Column</button>
  <button class="addRow">Add Row</button>
  <button class="removeRow">Remove Row</button>
  <table id="myTable">
    <thead>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Row 1, Column 1</td>
        <td>Row 1, Column 2</td>
        <td>Row 1, Column 3</td>
      </tr>
    </tbody>
  </table>

</body>

</html>

我真的不知道该怎么做,但我希望发生的是,当我单击添加行,然后单击添加列,添加的行包括在内,所以我可以添加5列在总数
就像我有3个原始行,当我再添加2行时,我希望它添加5列,但现在的情况是,当我有3个原始行,然后再添加2行时,只有3个原始行获得列

wgeznvg7

wgeznvg71#

在构建一个新的表之前,你需要获得表行的列数。所以我编辑了你的“addRowButton”事件:

addRowButton.addEventListener("click", function() {
  // Create a new row element
  const newRow = table.insertRow();

  var myTable = document.getElementById("myTable");
  var cellsCount = myTable.rows[0].cells.length;

  // Insert new cells
  for(var i = 0; i < cellsCount; i++) {
    const cell = newRow.insertCell(i);
    cell.innerHTML = "New Row, Column " + (i+1);
  }

});

相关问题