当<select>值发生变化时,如何根据值调用不同的函数?

时间:2015-05-18 15:03:51

标签: javascript knockout.js

我想在更改选择选项时调用不同的功能 这是标记: &lt; p&gt;每次选择更改时,我都希望调用不同的函数&lt; / p&gt; &lt; select data-bind =&#34; options:availableMeals,optionsText:&#39; name&#39;,value:selectedMeal,optionsValue:&#39; value&#39;,event:{change:onChange}&# 34;&GT; &LT; /选择&GT; 这是我的viewmodel: function ReservationsViewModel(){     var self = this;     self.availableMeals = ko.observableArray(         [          {name:&#34; Standard(sandwich)&#34;,value:0},          {name:&#34; Premium(龙虾)&#34;,价值:34.95},          {name:&#34; Ultimate(full zebra)&#34;,value:290}         ]     );     self.selectedMeal = ko.observable(self.availableMeals()[0]);     //当我换到sandwitch时我想要这个     self.onChange = function(){         警报(&#34;对于sandwitch&#34;);     };     //当我换成龙虾时我想要这个     self.onChange1 = function(){         警报(&#34;龙虾&#34;);     };     //当我改为终极时,我想要这个     self.onChange2 = function(){         警报(&#34;对于整个斑马&#34;);     }; } ko.applyBindings(new ReservationsViewModel()); 我知道我只使用change事件绑定onChange函数。在不同的选择上调用三种不同功能的方法是什么? 这是演示小提琴:http://jsfiddle.net/mLv42zkL/

1 个答案:

答案 0 :(得分:3)

使用一个函数onChange,然后根据selectedMeal的值调用其他函数。

例如:

function ReservationsViewModel() {
  var self = this;

  self.availableMeals = ko.observableArray(
    [{
      name: "Standard (sandwich)",
      value: 0
    }, {
      name: "Premium (lobster)",
      value: 34.95
    }, {
      name: "Ultimate (whole zebra)",
      value: 290
    }]
  );

  self.selectedMeal = ko.observable(self.availableMeals()[0]);

  self.onChange = function() {
    switch (self.selectedMeal()) {
      case 0:
        self.sandwichSelected();
        break;
      case 34.95:
        self.lobsterSelected();
        break;
      case 290:
        self.zebraSelected();
        break;
    }
  };

  self.sandwichSelected = function() {
    alert("for sandwich");
  };

  self.lobsterSelected = function() {
    alert("for lobster");
  };

  self.zebraSelected = function() {
    alert("for whole zebra");
  };
}

ko.applyBindings(new ReservationsViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>With every selection change I want a different function to be called</p>

<select data-bind="options: availableMeals, optionsText: 'name', value: selectedMeal, optionsValue: 'value', event: {change: onChange}">
</select>

Fiddle Demo