1

我要做的就是让 KnockOut 将两个文本框的值相加,然后将结果放入第三个。

我在这里有一个 JSFiddle:jsFiddle

我的 HTML 框是:

<input data-bind="value:AirportPickup" data-val="true" data-val-number="The field Airport Pickup £10 per person must be a number." data-val-required="The Airport Pickup £10 per person field is required." id="AirportPickup" name="AirportPickup" type="text" value="0" />

<input data-bind="value:PackedLunch" data-val="true" data-val-number="The field Packed Lunch £6.50 must be a number." data-val-required="The Packed Lunch £6.50 field is required." id="PackedLunch" name="PackedLunch" type="text" value="0" />

<input data-bind="value:Breakfast" data-val="true" data-val-number="The field Breakfast £6.00 must be a number." data-val-required="The Breakfast £6.00 field is required." id="Breakfast" name="Breakfast" type="text" value="0" />

...我的 jQuery 是:

$(document).ready(function () {

function AppViewModel() {
    this.AirportPickup = ko.observable("");
    this.PackedLunch = ko.observable("");
    this.Breakfast = AirportPickup + PackedLunch;
}
ko.applyBindings(new AppViewModel());
});

但是,当我将任何内容放入前两个文本框中时,什么也没有发生。

有人可以帮忙吗?

谢谢

4

3 回答 3

3

使用计算的 observable

http://jsfiddle.net/7kQP6/

$(document).ready(function () {

    function AppViewModel() {
        this.AirportPickup = ko.observable(0);
        this.PackedLunch = ko.observable(0);
        this.Breakfast = ko.computed(function () {
            return Number(this.AirportPickup()) + Number(this.PackedLunch())
        }, this);
    }
    ko.applyBindings(new AppViewModel());
});

请注意,此代码需要一些验证(例如,确保输入是数字)。

于 2013-07-12T14:51:10.127 回答
2

另一种方式可能是

http://jsfiddle.net/7kQP6/1/

只需在数据绑定中设置值

 <input data-bind="value:AirportPickup" data-val="true" data-val-number="The field Airport Pickup £10 per person must be a number." data-val-required="The Airport Pickup £10 per person field is required." id="AirportPickup" name="AirportPickup" type="text" value="0" />

<input data-bind="value:PackedLunch" data-val="true" data-val-number="The field Packed Lunch £6.50 must be a number." data-val-required="The Packed Lunch £6.50 field is required." id="PackedLunch" name="PackedLunch" type="text" value="0" />

<input data-bind="value:Number(AirportPickup()) + Number( PackedLunch())" data-val="true" data-val-number="The field Breakfast £6.00 must be a number." data-val-required="The Breakfast £6.00 field is required." id="Breakfast" name="Breakfast" type="text" value="0" />;
于 2013-07-12T14:57:14.213 回答
1

this.Breakfast 需要是一个计算出来的 observable:

this.Breakfast = ko.computed(function() {
 return this.AirportPickup + this.PackedLunch;
});
于 2013-07-12T14:52:21.030 回答