javascript KnockoutJS:在 Select 中的每个 Option 上调用的单击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12892066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:21:42  来源:igfitidea点击:

KnockoutJS: click event invoked on every Option in Select

javascriptknockout.js

提问by user1746507

I want Knockout to call an event whenever the user clicks an option in a SELECT element.

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

Here's my JavaScript:

这是我的 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());

Here's my HTML:

这是我的 HTML:

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

But when I run this, the application shows "hello" three times even though none of the options were actually clicked.

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

What am I doing wrong?

我究竟做错了什么?

回答by Artem Vyshniakov

You should use changebinding instead of clickand optionsTextbinding instead of optiontag and use functionin changebinding instead of just calling alert:

您应该使用changebinding 而不是clickoptionsTextbinding 而不是optiontag 并functionchangebinding 中使用而不是仅仅调用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());

Here is working example: http://jsfiddle.net/Q8QLX/

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

回答by gbs

The "alert" should be embedded in a function:

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

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