我正在使用Knockout生成一个循环遍历对象列表的表;但是,有一列我只想出现一次。在下面的示例中:
Group | Component | Description |
---------------------------------
A | Comp 1 | Desc 1 |
A | Comp 2 | Desc 2 |
B | Comp 3 | Desc 3 |
B | Comp 4 | Desc 4 |
我希望最终输出看起来像这样:
Group | Component | Description |
---------------------------------
A | Comp 1 | Desc 1 |
| Comp 2 | Desc 2 |
B | Comp 3 | Desc 3 |
| Comp 4 | Desc 4 |
有没有办法通过jQuery或其他框架来做到这一点?
修改
答案 0 :(得分:1)
Anoops回答有效,但我个人更喜欢避免内联计算。
因此,您可以将此计算卸载到函数,并通过$parent
绑定到viewmodel上的计算。
如果你想要重复0次,请不要忘记排序:)
var vm = function() {
var data = new ko.observableArray([
{ group: 'A', component: 'Component 1', description: 'Description 1' },
{ group: 'A', component: 'Component 2', description: 'Description 2' },
{ group: 'B', component: 'Component 3', description: 'Description 3' },
{ group: 'B', component: 'Component 4', description: 'Description 4' },
]);
function groupValue(index) {
var underlyingArray = data();
if(index == 0)
return underlyingArray[0].group;
return underlyingArray[index-1].group == underlyingArray[index].group
? "" : underlyingArray[index].group;
}
return {
data: data,
groupValue: groupValue
}
}
ko.applyBindings(new vm());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<thead>
<tr><th>Group</th><th>Component</th><th>Description</th></tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: $parent.groupValue($index())"></td>
<td data-bind="text: component"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
</table>
&#13;
答案 1 :(得分:0)
更改下面的代码,它会起作用。
<table>
<thead>
<tr><th>Group</th><th>Component</th><th>Description</th></tr>
</thead>
<tbody data-bind="foreach: myObj">
<tr>
<td data-bind="text: $index()-1 >= 0? ($parent.myObj[$index()-1].group == group? '' : group):group"></td>
<td data-bind="text: component"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
</table>
更新了小提琴,