【问题标题】:Fill current rows with default cells when adding new columns to the table向表中添加新列时用默认单元格填充当前行
【发布时间】:2016-10-29 04:43:51
【问题描述】:

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

【问题讨论】:

  • 对不起,我无法理解这个问题。我看到您在标题中附加了新列,但不在行中。也许是这样?

标签: javascript jquery


【解决方案1】:

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

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

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

【讨论】:

  • 对不起,这不起作用。我不能告诉你什么崩溃了,但是在使用你的代码之后,我的“AddRow”函数只有在我第一次按下添加行然后添加列时才开始工作。添加列后,它也添加了行。诡异的。但我把我的问题拍了一张,你可以在这里看到:imgur.com/a/nEpBQ
  • 添加为 sn-p。这不是你想要的行为吗?如果在您添加第一列之前它没有添加行,我的第一个猜测是您在某处有一些无效的标记。由于您没有发布标记,因此我发布了我在发布答案时想到的标记。 (单击运行代码 sn-p 按钮)。
猜你喜欢
  • 2016-08-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多