我正在尝试使用json对象数组中的thead
创建tr
。这是必需的,因为jQuery数据表需要它。
我可以使用以下脚本来执行此操作,但是会使用空白值创建tr。
$(function() {
var json = {
"Number": "10031",
"Description": "Solid Parts",
"Factory": "Factory1",
"LocationIn": "OutRack",
"Quantity": 18
}
var parsed = $.parseJSON(JSON.stringify(json));
console.log(parsed);
var $thead = $('#tableId').find('thead');
$.each(parsed, function(name, value) {
$thead.append('<tr>' + name + '</tr>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableId" class="table table-condensed responsive">
<thead>
</thead>
<tbody>
</tbody>
</table>
我需要使用数组名称创建一个表。示例:
<table id="tableId" class="table table-condensed responsive">
<thead>
<tr>Number</tr>
<tr>Description</tr>
<tr>Factory</tr>
<tr>LocationIn</tr>
<tr>Quantity</tr>
</thead>
<tbody>
</tbody>
</table>
答案 0 :(得分:1)
您不能直接向TR标签添加值,
您应该添加tr,然后将列值附加到TR中,
尝试以下类似方法。
$(function() {
var json = {
"Number": "10031",
"Description": "Solid Parts",
"Factory": "Factory1",
"LocationIn": "OutRack",
"Quantity": 18
}
var parsed = $.parseJSON(JSON.stringify(json));
console.log(parsed);
var $thead = $('#tableId').find('thead');
var tr = $("<tr>");
$thead.append(tr);
$.each(parsed, function(name, value) {
$(tr).append('<th>' + name + '</th>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableId" class="table table-condensed responsive" border="1">
<thead>
</thead>
<tbody>
</tbody>
</table>
答案 1 :(得分:0)
您非常亲密,只有一些错误 https://jsfiddle.net/k7arxht2/11/
var json = {
"Number": "10031",
"Description": "Solid Parts",
"Factory": "Factory1",
"LocationIn": "OutRack",
"Quantity": 18
}
var parsed = $.parseJSON(JSON.stringify(json));
var headers = Object.getOwnPropertyNames(parsed).map(function(hdr) {
return "<th>" + hdr + "</th>";
});
$('#tableId thead').append("<tr>" + headers + "</tr>");