KnockoutJS: click event invoked on every Option in Select

前端 未结 2 1331
无人及你
无人及你 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: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:

    
    
    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/

提交回复
热议问题