我是将html表格行加载为字符串,将其附加到表格主体并初始化数据表:
// ajax_data.response_message is a string, containing rows like: "<tr><td>1</td><td>Some data</td></tr><td>2</td><td>Some data 2</td></tr>"
contracts_table.find('tbody').empty().append(ajax_data.response_message);
data_table = contracts_table.DataTable({
fixedHeader: {
header: true,
footer: true
},
responsive: true,
aoColumnDefs: [{
'bSortable': false,
'aTargets': ['_nosort']
}],
bAutoWidth: false,
iDisplayLength: 20,
aLengthMenu: [[5, 10, 20, 50, 100], [5, 10, 20, 50, 100]],
}
});
当我在第一页上删除或添加行时,它工作正常:
// rows is an array like: ["1288", "3218", ...]
var remove_rows = function(rows) {
for (var key in rows) {
if (rows.hasOwnProperty(key)) {
console.log('remove: ');
console.log(data_table.row($('.check-single#' + rows[key] + '').closest('tr')).remove());
}
}
data_table.draw(false);
};
// contract_rows is a string, containing rows like: "<tr><td>1</td><td>Some data</td></tr><td>2</td><td>Some data 2</td></tr>"
var add_rows = function(contract_rows) {
var crows = contract_rows.split('</tr>');
for (var key in crows) {
if (crows.hasOwnProperty(key) && crows[key] != "") {
//
var new_row = crows[key] + '</tr>';
console.log('add: ');
console.log(data_table.row.add($(new_row)[0]));
}
}
data_table.draw(false);
};
在其他页面上,它成功删除了行,但是没有添加新行。我找不到原因。有人可以帮我这个,我会非常感激。
答案 0 :(得分:1)
我认为这种方法正在遭受竞争条件的影响,以及您没有利用DataTables并且正在有效地混合苹果和橙子这一事实。这个JSFiddle说明了你现在要做的事情:
$(document).ready(function() {
var mockData = "<tr><td>Sonya Frost</td><td>Software Engineer</td><td>Edinburgh</td><td>23</td><td>2008/12/13</td><td>$103,600</td></tr><tr><td>Jena Gaines</td><td>Office Manager</td><td>London</td><td>30</td><td>2008/12/19</td><td>$90,560</td></tr>"
peopleTable = $('#example');
setTimeout(function(){
peopleTable.find("tbody").empty().append(mockData)
}, 500);
var dt = peopleTable.DataTable();
});
如果您更改ajax结果以仅将数据作为数组或数组返回JSFiddle,并使用DataTable API clear
然后add
新数据,那么您应该发现事情要容易得多。
$(document).ready(function() {
var mockData = [
[
"Sonya Frost",
"Software Engineer",
"Edinburgh",
"23",
"2008/12/13",
"$103,600"
],
[
"Jena Gaines",
"Office Manager",
"London",
"30",
"2008/12/19",
"$90,560"
]
],
peopleTable = $('#example');
setTimeout(function(){
dt.clear().rows.add(mockData).draw();
}, 500);
var dt = peopleTable.DataTable();
});
希望有所帮助。