我有一个关于敲门的问题,这里是我的HTML和Javascript代码,你能告诉我我的代码有什么问题,当我点击复选框时相关的isWaived未选中
<input type="checkbox" data-bind="checked: isWaived(0)">
<div data-bind="visible: isWaived(0)" >
<div class="alert">
You have waived coverage for this member0.
</div>
</div>
这是我的javascript代码
function Member(idx, isWaived) {
var self = this;
self.idx = idx;
self.isWaived = ko.observable(isWaived);
}
function ReviewCartViewModel() {
var self = this;
// Editable data
self.members = ko.observableArray([
new Member(0, true),
new Member(1, false),
new Member(2, false),
new Member(3, false),
]);
self.isWaived = function (idx) {
for (var i in self.members()) {
var member = self.members()[i];
if (member.idx == idx)
return member.isWaived();
}
};
self.DoWave = function (idxs) {
for (var i in self.members()) {
var member = self.members()[i];
if (member.idx == idxs) {
member.isWaived(!member.isWaived());
//Send Ajax Request to waived the user
}
}
};
}
ko.applyBindings(new ReviewCartViewModel());
这是这个脚本的小提琴页面 http://jsfiddle.net/mohsenvafa/spMvd/
答案 0 :(得分:0)
用以下方法替换你的绑定(单选按钮上的checked
绑定和div上的visible
按钮):
members()[0].isWaived
问题在于Knockout可以从值isWaived(0)
读取,但它不能写到该值,因为它是评估函数的结果 - 这不是一个可观察的。我们在这里想要的可观察性是isWaived
的{{1}}属性,上面的语法是你如何将它交给Knockout。
答案 1 :(得分:0)
你的javascript可能有点过分了。使用正确的绑定,您可以从根模型中删除isWaived和DoWave函数。 Here is a jsfiddle of a working solution.
HTML
<!-- ko with:members()[0] -->
<div>
<input type="checkbox" data-bind="checked:isWaived" />
</div>
<div data-bind="visible:isWaived">
<div class="alert">
You have waived coverage for this member <span data-bind="text:idx"></span>.
</div>
</div>
<!-- /ko -->
的Javascript
function Member(idx, isWaived) {
var self = this;
self.idx = idx;
self.isWaived = ko.observable(isWaived);
}
function ReviewCartViewModel() {
var self = this;
// Editable data
self.members = ko.observableArray([
new Member(0, true),
new Member(1, false),
new Member(2, false),
new Member(3, false),
]);
}
ko.applyBindings(new ReviewCartViewModel());