添加和删​​除列表淘汰赛

时间:2014-09-12 09:11:01

标签: javascript knockout.js

我试图制作一个可以添加和减去值的计算器。同时,我希望用户能够添加和删除列表。我的添加和删除列表按钮不起作用。有人能帮助我吗?

这是我的javascript代码:

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

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

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

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

self.addValue = funtion() {
    self.selectedOperator.push(self.selectedOperator()[0]);
}

self.removeValue = function(val) {
    self.selectedOperator.remove(val)
}
}

ko.applyBindings(new ViewModel());

,这是我的HTML代码:

 <div id="MyCalc">
<table>
    <tbody data-bind="foreach: selectedOperator">
        <tr>
            <td>
                <label>Value1</label>
                <input type="text" data-bind="value: value1" />
            </td>
            <td>
                <select data-bind="options: mathOperator, selectedOptions: selectedOperator,"></select>
            </td>
            <td>
                <button data-bind="click: removeValue">Remove</button>
            </td>
        </tr>
        <tr>
            <td>
                <label>Value2</label>
                <input type="text" data-bind="value: value2" />
            </td>
            <td>
                <select data-bind="options: mathOperator, selectedOptions: selectedOperator,"></select>
            </td>
            <td>
                <button data-bind="click: removeValue">Remove</button>
            </td>
        </tr>
        <button data-bind="click:addvalue">Add Another Value</button>
    </tbody>
</table>
<div id="result">Total:<span data-bind="text: calculateValues" />
</div>

或者为了便于查看,这是jdfiddle链接。 http://jsfiddle.net/sqkr65td/

0 个答案:

没有答案