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

时间:2016-10-28 15:03:26

标签: 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单元格设置,填充缺少的..?

1 个答案:

答案 0 :(得分:0)

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

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

&#13;
&#13;
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"
      }
  }
&#13;
<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" />
&#13;
&#13;
&#13;