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

标签 javascript jquery

我创建一个 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 单元格中设置,填充缺失的单元格..?

最佳答案

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

那么像这样的事情应该可以解决问题(如果我没有理解正确,请发表评论,以便我可以删除或更新我的答案):

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" />

关于javascript - 向表格添加新列时,使用默认单元格填充当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40307921/

相关文章:

javascript - JavaScript 解析最合适的错误处理策略?

jquery - 如何在 "depends"以外的规则上使用 jquery 验证 "required"?

javascript - jquery菜单,悬停并显示:none

javascript - Jasmine 依赖注入(inject)

javascript - JQuery 单击事件在 <tr> 中仅起作用一次

JavaScript 事件不工作

javascript - 有没有办法在打开 WebSocket 时发送元数据?

javascript - 通过查找 id-javascript 更改 href

javascript - 拒绝在 jQuery ajax 中延迟

jQuery .delegate() 和 .undelegate()