如何更改数据表背后的数据
How to change the data behind DataTables
我有一个简单的JSFiddle来演示这个问题。
https://jsfiddle.net/ddehghan/j26d2pdx/2/如果我在2个不同的数据集之间切换数据表的数据,我会遇到脚本错误。我做错了什么吗?
如有任何帮助,不胜感激。
HTML代码:<table id="data-table">
<thead></thead>
<tbody></tbody>
</table>
<button id="reload1">load data 1</button>
<button id="reload2">load data 2</button>
JS代码:
var fillTable = function (data) {
console.log(data);
var columns = [];
$.each(data[0], function (key, value) {
columns.push({
"data": key,
"title": key
});
});
var $table = $('#data-table');
$table.DataTable({
"pageLength": 2,
"destroy": true,
"lengthChange": false,
"processing": true,
"data": data,
"columns": columns
});
};
$("#reload1").click(function (e) {
var data = [{
col1: 888,
col2: 999,
col3: 999
}, {
col1: 777,
col2: 999,
col3: 999
}, {
col1: 666,
col2: 999,
col3: 999
}, {
col1: 555,
col2: 999,
col3: 999
}, {
col1: 444,
col2: 999,
col3: 999
}];
fillTable(data);
});
$("#reload2").click(function (e) {
var data = [{
col1: 123,
col2: 456
}, {
col1: 123,
col2: 456
}, {
col1: 123,
col2: 456
}, {
col1: 123,
col2: 456
}];
fillTable(data);
});
这是因为Col3是空的。
看这把小提琴。
var fillTable = function (data) {
console.log(data);
var columns = [];
$.each(data[0], function (key, value) {
columns.push({
"data": key,
"title": key
});
});
var $table = $('#data-table');
$table.DataTable({
"pageLength": 2,
"destroy": true,
"lengthChange": false,
"processing": true,
"data": data,
"columns": columns
});
};
$("#reload1").click(function (e) {
var data = [{
col1: 888,
col2: 999,
col3: 999
}, {
col1: 777,
col2: 999,
col3: 999
}, {
col1: 666,
col2: 999,
col3: 999
}, {
col1: 555,
col2: 999,
col3: 999
}, {
col1: 444,
col2: 999,
col3: 999
}];
fillTable(data);
});
$("#reload2").click(function (e) {
var data = [{
col1: 123,
col2: 456,
col3: 999
}, {
col1: 123,
col2: 456,
col3: 999
}, {
col1: 123,
col2: 456,
col3: 999
}, {
col1: 123,
col2: 456,
col3: 999
}];
fillTable(data);
});
问题发生时,你的"表"有3个颜色,然后试图下降到2个颜色。
感谢Alan http://datatables.net/forums/profile/1/allan的回答。
所以这里的问题是表是用不同数量的列构造的。当您使用destroy时,它会在DOM中留下表,因此如果您首先单击data 1,您将拥有一个具有3列的表-然后加载data 2,配置只有两列,但HTML有三列。这就是问题所在
答案是使用destroy()DT方法和$().empty(): https://jsfiddle.net/j26d2pdx/7/
var $table = $('#data-table');if ( $.fn.dataTable.isDataTable( $table ) ) {
$table.DataTable().destroy();
$table.empty();
}
$table.DataTable({
"pageLength": 2,
"lengthChange": false,
"processing": true,
"data": data,
"columns": columns
});
相关文章:
- 用程序搜索JQuery数据表中的文本
- 要求输入在数据列表中
- 正在将数据主题添加到所有项目
- 函数参数中的数据与指定变量之间的任何性能差异
- 在VanillaJS中模拟模型双向数据绑定
- CSS-如何定位内容数据标题
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 无法在数据endVal中设置值=“”;{{ucount}}”;使用Angular JS的CountUp
- 序列化数据属性中对象的最可靠方法
- 如何将JSON数据导入我的ejs模板
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何将json数据显示为html
- 画布数据到图像
- 使用jquery将mysql数据获取到新的表行中
- 使用html中的外部javascript进行数据验证
- 有时数据是't显示在浏览器中
- React中的数据集表示
- Angular只从数组中获取所需的数据
- 将asp.net代码背后的数据发送到javascript函数
- 如何更改数据表背后的数据