我是Knockoutjs的新手,我正在尝试完成两件事:
A.如果ul#TrueList为空或ul#FalseList为空,则隐藏/删除#TrueListSection或#FalseListSection
B.在每个li中打印$ index
C.是否可以在每个li中使用$ index获得键值
<li>0 - hasCar</li>
<li>2 - hasTruck</li>
D.如果您知道解决问题的更好方法,例如,不要在下面做其他事情(而不更改我的视图模型),我也将不胜感激
foreach: [data.hasCar, data.HasPlain, data.hasTruck, data.Bike]
这是我的视图模型
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 :)无论如何,我使用了帖子中的代码并对其进行了编辑,现在它可以满足您的要求(我认为):
我做了什么:
相关更改:
// 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
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句