KnockoutJs:从下拉列表中获取价值

时间:2013-06-18 02:28:46

标签: javascript jquery html knockout.js knockout-2.0

我很难使用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);

1 个答案:

答案 0 :(得分:2)

那应该是

value:selectedLocation

value:selectedJobType

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

另外,在你的警报中,你需要viewModel.selectedJobType(),因为(a)它是viewModel不是全局的属性,(b)它是一个可观察的属性,所以你需要调用它来获取值。与selectedLocation相同。

这是一个有效的fiddle