1

我很难使用 Knockout JS 获取下拉列表的选定值

jsFiddle

HTML

     <select id="l" data-bind="options: locations, value=selectedLocation"></select>
     <select id="j" data-bind="options: jobTypes, value=selectedJobType"></select>
     <button data-bind="click: myFunction"> Display </button>

脚本

       var viewModel = {
            locations: ko.observableArray(['All Locations', 'Sydney', 'Melbourne', 'Brisbane', 'Darwin', 'Perth', 'Adelaide']),
            selectedLocation: ko.observable(),

            jobTypes: ko.observableArray(['All Vacancies', 'Administration', 'Engineering', 'Legal', 'Sales', 'Accounting']),
            selectedJobType: ko.observable(),

            myFunction: function() {
                alert(selectedJobType + ' ' +selectedLocation );
            }
        };
        // ... then later ...
        //viewModel.availableCountries.push('China');
        // Adds another option
        ko.applyBindings(viewModel);
4

1 回答 1

2

那应该是

value:selectedLocation

和:

value:selectedJobType

在你的绑定。绑定使用与对象字面量相同的语法。

另外,在您的警报中,您需要viewModel.selectedJobType(),因为(a)它是非viewModel全局属性,并且(b)它是可观察的,因此您需要调用它来获取值。对selectedLocation.

这是一个工作小提琴

于 2013-06-18T03:00:31.307 回答