13

我希望 Knockout 在用户单击 SELECT 元素中的选项时调用事件。

这是我的 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”。

我究竟做错了什么?

4

2 回答 2

16

您应该使用changebinding 而不是clickoptionsTextbinding 而不是optiontag 并使用functionin changebinding 而不是仅仅调用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/

于 2012-10-15T10:08:46.140 回答
3

“警报”应该嵌入到一个函数中:

<select data-bind="foreach: availableMeals, event: {change: function () {   alert('hello'); } }">
    <option data-bind="text: mealName " />
</select>
于 2012-10-15T10:55:01.927 回答