我有以下淘汰赛和HTML:
<table>
<tbody data-bind="foreach: $root.selectedGroup().services">
<!-- ko if: ($index() % 2 === 0) -->
<tr>
<td data-bind="text:1">
</td>
<!-- /ko -->
<!-- ko ifnot: ($index() % 2 === 0) -->
<td data-bind="text: 0"></td>
</tr>
<!-- /ko -->
</tbody>
</table>
我只得到1,但没有0。我的数组中有5个项目
我应该展示
1 0
1 0
1
但我只有
1
1
1
任何想法?
答案 0 :(得分:1)
这是一种方法
<table>
<tbody data-bind="foreach: $root.services">
<!-- ko if: ($index() % 2 === 0) -->
<tr>
<!-- ko with: $root.services[$index()] -->
<td data-bind="text:$data"></td>
<!-- /ko -->
<!-- ko with: $root.services[$index()+1] -->
<td data-bind="text:$data"></td>
<!-- /ko -->
</tr>
<!-- /ko -->
</tbody>
它通过在数组中向前看下一个项目然后在每个第二个项目上呈现行来工作。
我认为最好在你的viewmodel中对此进行建模,但这是一个折磨的解决方案。
答案 1 :(得分:0)
如果条件
,放置容器的问题会有轻微的问题你写的是if / ifnot如果/ if之类的条件,那么每行输出0或1都不是
<table>
<tbody data-bind="foreach: $root.selectedGroup().services">
<tr>
<!-- ko if: ($index() % 2 === 0) -->
<td data-bind="text:1">
</td>
<!-- /ko -->
<!-- ko ifnot: ($index() % 2 === 0) -->
<td data-bind="text: 0"></td>
<!-- /ko -->
</tr>
</tbody>
</table>
工作小提琴 here
答案 2 :(得分:0)
Knockout似乎在这里做了一些奇怪的事情,但说实话,这种使用if / ifnot绑定来捏造2列布局以有条件地渲染开放和关闭<tr>
节点似乎有点过于复杂。
您可以做的是使用计算的可观察量将您的单位列表重新修改为适当的行/列:
this.services = ["bar","foo","bar","foo","bar","foo","bar","foo","bar","foo","bar","foo","bar","foo"];
this.serviceRows = ko.computed(function(){
var result = [],
row,
colLength = 2;
//loop through items and push each item to a row array that gets pushed to the final result
for (var i = 0, j = this.services.length; i < j; i++) {
if (i % colLength === 0) {
if (row) {
result.push(row);
}
row = [];
}
row.push(this.services[i]);
}
//push the final row
if (row) {
result.push(row);
}
return result;
}, this);
然后以更直接的方式呈现模板:
<table>
<tbody data-bind="foreach: serviceRows">
<tr data-bind="foreach: $data">
<td data-bind="text: ($index() % 2)"></td>
</tr>
</tbody>
</table>