计算器使用淘汰赛

时间:2014-09-12 06:28:10

标签: javascript knockout.js

我想制作一个简单的计算器。用户可以输入数字,同时可以使用下拉列表选择数学运算符(如加减)。

我有一个问题,使下拉列表作为一个功能。用户选择添加时的含义,可以计算用户输入的数字。有人能帮助我吗?

 var CalcOperation = function (num,operation) {
    var self = this;
    self.num = num;
    self.operation = operation;
    $.each(operationCalc) {
        if (operationName == "Addition") {
            self.sum = ko.computed(function(){
            return parseFloat(self.num()) + parseFloat(self.addNum());
            });
        } else {
            self.minus = ko.computed(function(){
            return self.num() - self.minusNum();
            });
        }
    }
 }
 var Calculator = function () {
    var self = this;
    self.operationCalc = [
        { val:0, operationName: "Addition"},
        { val:1, operationName: "Subtraction"}
    ];    

    self.math = ko.observableArray([
        new CalcOperation("", self.operationCalc[0]),
        new CalcOperation("", self.operationCalc[0])
    ]);
  }

1 个答案:

答案 0 :(得分:1)

制作了一个可以帮助你的小型JSFiddle。 http://jsfiddle.net/djve/bbnmtLx2/1/

var ViewModel = function() {
    var self = this;

    self.value1 = ko.observable(0),
    self.value2 = ko.observable(0),
    self.mathOperator = ko.observableArray(['+', '-']);
    self.selectedOperator = ko.observable('+');

    self.calculateValues = ko.computed(function(){
        var selectedOperator = self.selectedOperator(),
            value1 = self.value1(),
            value2 = self.value2();

        switch(selectedOperator){
            case '+': 
                return parseInt(value1) + parseInt(value2);
            case '-':
                return parseInt(value1) - parseInt(value2);
        }
    });
};

ko.applyBindings(new ViewModel());