gpt4 book ai didi

javascript - 如何使用 Knockout 使列值只出现一次?

转载 作者:行者123 更新时间:2023-11-29 23:53:24 25 4
gpt4 key购买 nike

我正在使用 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 或其他框架做到这一点?

编辑

示例代码: https://jsfiddle.net/on6Lby1c/

最佳答案

Anoops 答案有效,但我个人更喜欢避免内联计算。因此,您可以将此计算卸载到一个函数,并通过 $parent 绑定(bind)到 View 模型上的函数。

如果你想要 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>

https://jsfiddle.net/fv9x3s20/

关于javascript - 如何使用 Knockout 使列值只出现一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263905/

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