向下钻取表单字段,逐渐显示字段。虽然我已经找到了使它们在页面上一次出现的逻辑,包括一个简单的切换,但是当点击“No”时(并且所有字段都清除),问题是将所有可观察对象重置为其原始状态)。目前,如果第二次点击“是”(在完成表格之后,然后决定“否”),则所有字段立即重新出现而不是逐渐出现。 http://jsfiddle.net/hotdiggity/JJ6f6/
淘汰赛模特:
var ViewModel = function () {
var self = this;
self.showField1 = ko.observable(true);
self.showField2 = ko.observable(false);
self.showField3 = ko.observable(false);
self.showField4 = ko.observable(false);
self.yesOrNo = ko.observable("");
self.hasValue = ko.observable("");
self.toggleCalc = ko.observable("");
self.showField2 = ko.computed(function () {
return self.yesOrNo() == 'yes';
});
self.showField3 = ko.computed(function () {
self.showField4(false);
return ( !! self.hasValue());
});
self.toggleCalc = function () {
self.showField4(!self.showField4());
};
};
ko.bindingHandlers.fadeVisible = {
init: function (element, valueAccessor) {
var value = valueAccessor();
$(element).toggle(ko.utils.unwrapObservable(value));
},
update: function (element, valueAccessor) {
var value = valueAccessor();
ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
}
};
ko.applyBindings(new ViewModel());
HTML:
<div class='list-inputs'>
<h2>Drilldown toggle interaction</h2>
<!--LEVEL 1-->
<div data-bind='fadeVisible: showField1'>(L1) Choose one to display more options:
<p>
<label>
<input type='radio' name="type" value='yes' data-bind='checked: yesOrNo' />Yes</label>
<label>
<input type='radio' name="type" value='no' data-bind='checked: yesOrNo' />No</label>
</p>
<!--LEVEL 2-->
<div data-bind='fadeVisible: showField2'>
<p>(L2) Enter input and click off:
<input type="text" data-bind='value: hasValue' />
</p>
<!--LEVEL 3-->
<div data-bind='fadeVisible: showField3'>
<p><span>(L3) Earnings:</span>
<input type="text" /> <a data-bind="click: toggleCalc" href="#">Toggle calculator</a>
</p>
<!--LEVEL 4-->
<div data-bind='fadeVisible: showField4'>
<br />
<p><b>(L4) Calculator</b>
</p>
<p><span>Input 1:</span>
<input type="text" />
</p>
<p><span>Input 2:</span>
<input type="text" />
</p>
<p><span><b>Total:</b></span>
<input type="text" />
</p>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
通过进行两项更改,我得到了这个(我想你想要的方式):
我将yesOrNo
字段初始化为“否”。
当用户将其L1响应更改为“否”时,更改showField2
以清除“L2”文本框的值。这会导致表单“重新初始化”,因此下次选择“是”时,它将开始清理。
self.showField2 = ko.computed(function () {
var isNo = self.yesOrNo() == 'no';
if( isNo )
{
self.hasValue('');
}
return !isNo;
});