[英]DataTable Javascript does not add row
我正在尝试使用此方法https://datatables.net/examples/api/add_row.html ,我的表由几个不同的HTML元素组成,它们属于select和input类型。 我在这里将其简化为一个输入和一列。 我的目标是单击“添加行”按钮,然后将包含所有元素的精确行添加到表中。 但是,当我单击“添加行”按钮时,条目的数量增加了,在控制台中没有错误或警告,但是仍然看不到表中添加了新行。
<table id="myTable">
<thead>
<tr>column header 1</tr>
<tr>column header 2</tr>
</thead>
<tbody>
<tr id="myRow">
<td id="colorField>
<input id="color">
</td>
</tr>
</tbody>
</table>
JS部分:
$(document).ready(function() {
var t = $('#myTable').DataTable();
$('#addRow').on('click', function(){
var jRow = $('#myRow');
jRow.id = "myRow2"; //I thought about changing the id but also not effective
t.row.add(jRow).draw();
});
});
HTML和JavaScript存在一些问题。
HTML格式不正确-您有两个未定义为标题的列标题,然后只有一个未正确关闭的数据单元格。
尝试这个:
<table id="myTable">
<thead>
<tr>
<th>column header 1</th>
<th>column header 2</th>
</tr>
</thead>
<tbody>
<tr id="myRow">
<td id="colorField">
<input id="color" type="text"/>
</td>
<td></td>
</tr>
</tbody>
</table>
<button id="addRow">Add Row</button>
然后您的JS也需要进行一些更改。 您可以将jQuery对象作为一行添加,例如:
$(document).ready(function() {
var t = $('#myTable').DataTable();
$('#addRow').on('click', function(){
var jRow = $('<tr>').append('<td>Cell 1</td>','<td>Cell 2</td>');
jRow.attr('id', 'myRow2');
t.row.add(jRow).draw();
});
});
它们是您的HTML标记的一些问题。 例如:
<tr>column header 1</tr><tr>column header 2</tr>
应该
<tr><th>Header 1</th><th>Header 2</th></tr>
<tr>
是行, <th>
是行标题。
还请确保id="colorField
关闭这些语句id="colorField"
忘记最后的( "
)。
这里的工作示例:
$(document).ready(function() { var $table = $('#table').DataTable(), counter = $('#table').find("tbody > tr").length; // get current number of rows $('.addRow').on('click', function() { var $row = $('.row0'), // find the default row newRow = $row.clone().attr("class", "row" + counter); // clone the row and change the class $table.row.add(newRow).draw(); // add to the table counter++; // increase counter }); });
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> <table id="table"> <thead> <tr> <th>Header 1</th> <th>Header 2</th> </tr> </thead> <tbody> <tr class="row0"> <td class="field-label">Enter a color:</td> <td class="field"> <input class="color"> </td> </tr> </tbody> </table> <button class="addRow">Add Row</button>
在$row.clone().attr("class", "row" + counter);
在这一行中,您无需更改类,但是如果您想为其分配任何JavaScript事件,则可以.clone()
但是您需要.clone()
删除该行与表的关联)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.