我正在尝试设置一个可以禁用输入的knockout observable,如果另外两个输入都不在1到30之间。现在当我在jsFiddle中运行代码时,我的输入被禁用。不幸的是,我永远无法重新启用输入。以下是jsFiddle上的代码,感谢您的帮助。
HTML
<!-- This is a *view* - HTML markup that defines the appearance of your
UI -->
<p>Alcohol Days:
<input data-bind="value: alcoholDays" />
</p>
<p>Alcohol 5+ Days:
<input data-bind="value: alcoholFivePlusDays" />
</p>
<p>Alcohol 4- Days:
<input data-bind="value: alcoholFourLessDays" />
</p>
<p>Drug Days:
<input data-bind="value: drugDays" />
</p>
<p>Both Days:
<input data-bind="value: bothDays, enable: enableBothDays" />
</p>
<p>Enable Both Days: <strong data-bind="text: enableBothDays"></strong>
</p>
<p>Alcohol Days: <strong data-bind="text: alcoholDays"></strong>
</p>
<p>Drug Days: <strong data-bind="text: drugDays"></strong>
</p>
<button data-bind="click: capitalizeLastName">Go caps</button>
的javascript
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
var self = this;
self.alcoholDays = ko.observable("");
self.alcoholFivePlusDays = ko.observable("");
self.alcoholFourLessDays = ko.observable("");
self.drugDays = ko.observable("");
self.bothDays = ko.observable("");
self.enableBothDays = ko.computed(function () {
if ((parseInt(self.alcoholDays) > 0 && parseInt(self.alcoholDays) <= 30) && (parseInt(self.drugDays) > 0 && parseInt(self.drugDays) <= 30)) {
return true;
} else {
return false;
}
}, self);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
瓦德
答案 0 :(得分:1)
hi check this fiddle 我解决了问题。
1。)清除小提琴中的绑定错误
2。)重新构建计算的可观察
self.enableBothDays = ko.computed({
read: function() {
alert('In');
var alcDays = Number(self.alcoholDays());
var drgDays = Number(self.drugDays());
alert(alcDays+','+drgDays);
var temp = false;
if (alcDays > 0 && alcDays <= 30 && drgDays > 0 && drgDays <= 30) {
temp = true;
} else {
temp = false;
}
alert(temp);
return temp;
}
});
3.)更改了启用条件
将其标记为答案
答案 1 :(得分:1)
固定小提琴 http://jsfiddle.net/SNv6n/20/
您正在调用self.alcoholDays而不是self.alcoholDays()。如果将括号添加到计算中的那些调用中并添加函数'capitalizeLastName',则可以正常工作。
self.capitalizeLastName = function () {
alert('TODO');
}
self.enableBothDays = ko.computed(function () {
if ((parseInt(self.alcoholDays()) > 0 && parseInt(self.alcoholDays()) <= 30) && (parseInt(self.drugDays()) > 0 && parseInt(self.drugDays()) <= 30)) {
return true;
} else {
return false;
}
}, self);
答案 2 :(得分:0)
使用它 enable:enableBothDays()== true 要么 enable:enableBothDays == true