gpt4 book ai didi

jquery - 将列标题从数组添加到jquery数据表

转载 作者:行者123 更新时间:2023-12-01 07:52:44 24 4
gpt4 key购买 nike

我正在 jquery 中创建一个数据表。我有一个字符串数组,其中包含标题的标题。我想将这些标题添加到数据表中。我怎样才能做到这一点?

这是我的代码:-

html 代码:-

<table border="1" id="mDataTable" class="display" cellspacing="1" cellpadding="1" width="100%">
<thead>
<tr>

</tr>
</thead>
<tbody>

</tbody>
</table>

jquery 代码:-

 var columnArray = jsonArray[1];
var titleArray = [];
for (var j = 0; j < columnArray.length; j++) {

var parsedJson = $.parseJSON(JSON.stringify(columnArray[j]))
var mTitles = parsedJson["name"];
titleArray.push(mTitles);

}


$('#mDataTable').DataTable({

"columns": titleArray
});

titleArray = ["美国", "印度", "中国", "日本"]

jquery[1] = "Columns":[{"name":"ID","field":"id"},{"name":"America","field":"america"},{"name":"India","field":"india"},{"name":"China","field":"china"},{"name":"Japan","field":"japan"}],

执行上述操作时出现错误

Uncaught TypeError: Cannot use 'in' operator to search for '10' in America

编辑

根据 CerilBoss 的回答,我得到了这样的表格

enter image description here

我是 jquery 新手,希望得到任何帮助。

最佳答案

在初始化dataTable之前附加 header 数据

FIDDLE

代码

var jsonArray = {"Columns":[{"name":"ID","field":"id"},{"name":"America","field":"america"},{"name":"India","field":"india"},{"name":"China","field":"china"},{"name":"Japan","field":"japan"}]};
var columnArray = jsonArray['Columns'];
var titleArray = [];
$('table thead tr').empty();
for (var j = 0; j < columnArray.length; j++) {
var parsedJson = $.parseJSON(JSON.stringify(columnArray[j]))
var mTitles = parsedJson["name"];
$('table thead tr').append("<th>"+ mTitles +"</th>");
};
$('table').DataTable();

已更新 FIDDLE

更新代码

var jsonArray = {"Columns":[{"name":"ID","field":"id"},{"name":"America","field":"america"},{"name":"India","field":"india"},{"name":"China","field":"china"},{"name":"Japan","field":"japan"}]};
var columnArray = jsonArray['Columns'];
var titleArray = [];
for (var j = 0; j < columnArray.length; j++) {
var temp = {};
temp['title'] = columnArray[j]["name"];
titleArray.push(temp);
};
$('table').DataTable({ "columns": titleArray});

UDPATE

查看最新的fiddle

关于jquery - 将列标题从数组添加到jquery数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27700102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com