KnockoutJS:在Select中的每个Option上调用click事件 [英] KnockoutJS: click event invoked on every Option in Select
本文介绍了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屋!
查看全文