KnockoutJS:在Select中的每个Option上调用click事件 [英] KnockoutJS: click event invoked on every Option in Select

查看:425
本文介绍了KnockoutJS:在Select中的每个Option上调用click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的JavaScript:

Here's my 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三次,即使这些选项都没有实际点击了。

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

我做错了什么?

推荐答案

你应该使用更改绑定而不是单击 optionsText 绑定选项标记并在中使用函数更改绑定而不是只需调用 alert

You should use change binding instead of click and optionsText binding instead of option tag and use function in change binding instead of just calling 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/

这篇关于KnockoutJS:在Select中的每个Option上调用click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆