2016-10-28 50 views
1

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

+0

对不起,我不明白这个问题。我看到你在标题中追加新列,但不在行中。也许呢? – zozo

回答

0

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

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

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

+0

对不起,这没有工作。我不能告诉你什么崩溃,但使用你的代码后,我的“AddRow”函数才开始工作,只有当我第一次按添加行,然后添加列。添加列后,它也添加了行。奇怪的。但是我拍了一张我的问题的照片,你可以在这里看到它:http://imgur.com/a/nEpBQ – Garzec

+0

添加为片段。这不是你想要的行为吗?如果它不添加行直到添加第一列,我的第一个猜测是你的某处有一些无效的标记。由于您没有发布标记,因此我张贴了答案时发布了我想到的标记。 (点击Run code snippet按钮)。 – zozo

相关问题