我有一个由动态sql数据填充的observableArray
。因此,返回的列可能随时都有所不同。
我想在HTML表格中显示SQL结果。但是,以下内容无效。
这就是我希望输出看起来......
var viewModel = function(data) {
var self = this;
// variables
self.taskRecordOverview = ko.observableArray([
{
"Entity": "DEMO",
"Period": "2017-07-31T00:00:00",
"Level": "Level 3",
"Addendum Errors": null,
"Cash Process": "Created",
"Corporate Actions": null,
"Expenses": null
},
{
"Entity": "DEMO",
"Period": "2017-07-31T00:00:00",
"Level": "Level 5",
"Addendum Errors": "Created",
"Cash Process": "Created",
"Corporate Actions": "Created",
"Expenses": "Created"
},
{
"Entity": "SP00",
"Period": "2017-07-31T00:00:00",
"Level": "Level 5",
"Addendum Errors": "Created",
"Cash Process": "Approved",
"Corporate Actions": "Created",
"Expenses": "Created"
}
]);
};
ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>??</th>
</tr>
</thead>
<tbody data-bind="foreach: taskRecordOverview">
<tr>
<td data-bind="text: $data"></td>
</tr>
</tbody>
</table>
&#13;
答案 0 :(得分:0)
在foreach
的{{1}}循环中,您需要遍历每个对象的taskRecordOverview
并显示该值。您可以使用Object.keys
工作片段:
keys
&#13;
var viewModel = function() {
var self = this;
self.taskRecordOverview = ko.observableArray([{
"Entity": "DEMO",
"Period": "2017-07-31T00:00:00",
"Level": "Level 3",
"Addendum Errors": null,
"Cash Process": "Created",
"Corporate Actions": null,
"Expenses": null
},
{
"Entity": "DEMO",
"Period": "2017-07-31T00:00:00",
"Level": "Level 5",
"Addendum Errors": "Created",
"Cash Process": "Created",
"Corporate Actions": "Created",
"Expenses": "Created"
},
{
"Entity": "SP00",
"Period": "2017-07-31T00:00:00",
"Level": "Level 5",
"Addendum Errors": "Created",
"Cash Process": "Approved",
"Corporate Actions": "Created",
"Expenses": "Created"
}
]);
};
ko.applyBindings(new viewModel());
&#13;
td, th {
border: 1px solid #dddddd;
}
&#13;
<强> Here's a fiddle 强>
如果嵌套的<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<!--Only one object is enough for header-->
<tr data-bind="foreach:Object.keys(taskRecordOverview()[0]),visible:taskRecordOverview().length > 0">
<th data-bind="text:$data"></th>
</tr>
</thead>
<tbody data-bind="foreach: taskRecordOverview">
<!--Get the keys in each object and loop through them-->
<tr data-bind="foreach: Object.keys($data)">
<!--Get the "value" for a key-->
<td data-bind="text: $parent[$data]"></td>
</tr>
</tbody>
</table>
和$data
binding contexts令人困惑,我们可以alias foreach items using as
使其更加清晰:
$parent
我知道这是一个古老的问题,但这是一个有趣的问题,答案将来有希望帮助其他人:)