向表中添加新列时,用默认单元格填充当前行

Fill current rows with default cells when adding new columns to the table

本文关键字:填充 单元格 默认 添加 新列时      更新时间:2023-09-26

我创建了一个HTML表格,并在按钮事件上添加行和列。这是我的代码:

 function AddColumnToDataTable(){
      $('#tableHeader').append("<th> Header </th>").attr("contenteditable", true);
// Add a new ColumnHeader and set the property "editable"
    }
    function AddRowToDataTable(){
      var count = $('#tableHeader').find("th").length;
// Get the count of Columns in the table
      var newRow = $('#tableBody').append("<tr></tr>");
// Add a new Row
      for(var i = 0; i < count ; i++){
          newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
// Fill the cells with a default text and set the property "editable"
      }
    }

所以我想在添加新列时在旧行中设置新的单元格。使用默认文本自动填充行。

我必须计数索引吗?我有x列,在第y行中设置了z个单元格,填充缺失的。div ?

如果我正确理解了这个问题,您需要在当前行中添加新列也对吗?

然后像这样的东西应该做的技巧(如果我没有理解正确,请评论,以便我可以删除或更新我的答案):

function AddColumnToDataTable() {
      $('#tableHeader').append("<th>Header</th>").attr("contenteditable", true); // Add a new ColumnHeader and set the property "editable"
      $('#tableBody').find("tr").each(function() {
          $(this).append('<td>Content</td>');
      });
 }
function AddRowToDataTable(){
      var count = $('#tableHeader').find("th").length;
// Get the count of Columns in the table
      var newRow = $('#tableBody').append("<tr></tr>");
      for(var i = 0; i < count ; i++){
          newRow.find('tr').last().append("<td>Content</td>").attr("contenteditable", true);
// Fill the cells with a default text and set the property "editable"
      }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr id="tableHeader"><th>Header</th></tr>
  <tbody id="tableBody">
  </tbody>
</table>
<input onclick="AddColumnToDataTable();" type="button" value="Column" />
<input onclick="AddRowToDataTable();" type="button" value="Row" />