KnockoutJS: click event invoked on every Option in Select

前端 未结 2 1330
无人及你
无人及你 2021-02-07 15:41

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

Here\'s my JavaScript:

function ReservationsViewModel() {
    t         


        
相关标签:
2条回答
  • 2021-02-07 16:23

    The "alert" should be embedded in a function:

    <select data-bind="foreach: availableMeals, event: {change: function () {   alert('hello'); } }">
        <option data-bind="text: mealName " />
    </select>
    
    0 讨论(0)
  • 2021-02-07 16:25

    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());
    

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

    0 讨论(0)
提交回复
热议问题