KnockoutJS:在Select中的每个Option上调用click事件

时间:2012-10-15 08:46:01

标签: javascript knockout.js

每当用户单击SELECT元素中的选项时,我希望Knockout调用一个事件。

这是我的JavaScript:

function ReservationsViewModel() {
    this.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];
}

ko.applyBindings(new ReservationsViewModel());

这是我的HTML:

<select data-bind="foreach: availableMeals">
    <option data-bind="text: mealName, click: alert('hello')" />
</select>

但是当我运行它时,即使没有实际点击任何选项,应用程序也会显示“hello”三次。

我做错了什么?

2 个答案:

答案 0 :(得分:15)

您应该使用change绑定而不是clickoptionsText绑定而不是option标记,并在function绑定中使用change而不是只需致电alert

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

function Meal(name, price){
    var self = this;

    self.mealName = name;
    self.price =  price;    
}

function ReservationsViewModel() {
    var self = this;
    self.availableMeals = ko.observableArray(
        [new Meal("Standard (sandwich)", 0),
         new Meal("Premium (lobster)", 34.95),
         new Meal("Ultimate (whole zebra)", 290)]);


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

    self.onChange = function() {
        alert("Hello");
    };
}

ko.applyBindings(new ReservationsViewModel());

以下是工作示例:http://jsfiddle.net/Q8QLX/

答案 1 :(得分:2)

“警报”应嵌入功能中:

<select data-bind="foreach: availableMeals, event: {change: function () {   alert('hello'); } }">
    <option data-bind="text: mealName " />
</select>