我是 Knockoutjs 的新手,我正在尝试完成两件事:
A.如果 ul#TrueList 为空或 ul#FalseList 为空,则隐藏/删除 #TrueListSection 或 #FalseListSection
B.打印出每个li中的$index
C.是否可以获取每个li中带有$index的键值
<li>0 - hasCar</li>
<li>2 - hasTruck</li>
D.如果您知道更好的解决方法,我也将不胜感激,例如,不做下面的事情,而是做其他事情(不改变我的 View 模型)
foreach: [data.hasCar, data.HasPlain, data.hasTruck, data.Bike]
这是我的 View 模型
var ViewModel = function() {
var self = this;
this.data = {
hasCar: true,
hasPlain: false,
hasTruck: true,
hasBike: false
};
};
这是我的 HTML:
<div id="TrueListSection">
<h2><b>Has</b></h2>
<ul id="TrueList" data-bind="foreach: [data.hasCar, data.HasPlain, data.hasTruck, data.Bike]">
<!-- ko if: $data -->
<li data-bind="text: $index"></li>
<!-- /ko -->
</ul>
</div>
<hr/>
<div id="FalseListSection">
<h2><b>Does Not Have</b></h2>
<ul id="FalseList" data-bind="foreach: [data.hasCar, data.HasPlain, data.hasTruck, data.Bike]">
<!-- ko ifnot: $data -->
<li data-bind="text: $index"></li>
<!-- /ko -->
</ul>
</div>
它当前抛出以下错误:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: $index is not defined;
Bindings value: text: $index
这是我的 JSFiddle:http://jsfiddle.net/tuJtF/3/
提前非常感谢您。
最佳答案
我认为您提供了错误的 fiddle :)无论如何,我使用了您帖子中的代码并对其进行了编辑,它现在可以满足您的要求(我认为):
我做了什么:
- 更新您的 knockout 库。您链接的版本似乎不支持 $index.html我链接了 Knockout 3.0,这解决了您的要求 B。
- 我更改了你的 View 模型来修复需求 D。我使用了一个可观察数组,现在在你的 foreach 绑定(bind)中使用。 Observable 数组可以直接传递到 foreach 中,而之前使用的对象不能直接传递到 foreach 中。
- 可观察数组充满了具有描述和值的对象。我以这种方式更改了您的数据以满足要求 C:打印键值。
- 我创建了计算可观察量,它返回可观察数组,其中仅包含原始数组中的 true 或 false 值。这样做是为了满足要求 A(我只需检查相应数组的长度即可知道该部分是否应该可见),并且还可以使您的绑定(bind)代码更清晰。
相关变更:
// Changed the structuring of your data to use observable arrays and include the description property so you can bind against it
this.data = ko.observableArray([
{ description: 'hasCar', value: true },
{ description: 'hasPlain', value: false },
{ description: 'hasTruck', value: true },
{ description: 'hasBike', value: false }
]);
// Made two computed observables so you can separate the true from the false values more easily.
this.trueData = ko.computed({
read: function () {
return ko.utils.arrayFilter(this.data(), function (item) {
return item.value === true;
});
},
owner: this
});
this.falseData = ko.computed({
read: function () {
return ko.utils.arrayFilter(this.data(), function (item) {
return item.value === false;
});
},
owner: this
});
关于knockout.js - knockout : foreach binding with filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20973837/