Knockout.js knockoutjs:foreach与过滤器的绑定
我是Knockoutjs新手,我正在努力完成两件事: A.如果ul#TrueList为空或ul#FalseList为空,则隐藏/删除#TrueListSection或#FalseListSection B.在每个li中打印$indexKnockout.js knockoutjs:foreach与过滤器的绑定,knockout.js,Knockout.js,我是Knockoutjs新手,我正在努力完成两件事: A.如果ul#TrueList为空或ul#FalseList为空,则隐藏/删除#TrueListSection或#FalseListSection B.在每个li中打印$index <li>0 - hasCar</li> <li>2 - hasTruck</li> C.是否可以在每个li中使用$index获取键值 <li>0 - hasCar</li> <li&g
<li>0 - hasCar</li>
<li>2 - hasTruck</li>
C.是否可以在每个li中使用$index获取键值
<li>0 - hasCar</li>
<li>2 - hasTruck</li>
这是我的视图模型
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>
下面是我的JSFIDLE:
非常感谢您。我认为您提供的小提琴是错误的:)无论如何,我使用了您文章中的代码并对其进行了编辑,现在它可以满足您的需要(我认为): 我所做的:
// 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
});
你的小提琴指向完全不同的代码?你使用的是什么浏览器?非常感谢,它工作得非常棒。顺便说一句,我修复了我的小提琴链接:)很高兴听到!在这种情况下,请将答案标记为已接受的解决方案:)给我一些代表,并让其他人知道您的问题已得到回答。
// 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
});