knockout.js – knockoutjs如何获取所选的选项arrayObject

前端之家收集整理的这篇文章主要介绍了knockout.js – knockoutjs如何获取所选的选项arrayObject前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想获得所选的选项对象
<select data-bind="options: availableCountries,value: selectedCountry,event: { select: onSelect}"></select>


<script type="text/javascript">
    // Constructor for an object with two properties
    var Country = function(name,population) {
        this.countryName = name;
        this.countryPopulation = population;   
    };       

    var viewmodel = {
        availableCountries : ko.observableArray([
            new Country("UK",65000000),new Country("USA",320000000),new Country("Sweden",29000000)
        ]),selectedCountry : ko.observable(),// Nothing selected by default
        onSelect: function(){
              console.log(viewmodel.selectedCountry)
              // it is showing just an country name and what i what is whole object
              // e.g. { "UK",65000000 } // that is selected option in selected Box

        }

    };
</script>

解决方法

您不必将select事件添加到控件.更有效的方法订阅selectedCountry更改:
viewmodel.selectedCountry.subscribe(function (data) {
        console.log(data)
    });

如果您不希望默认选择任何国家/地区,则必须将optionsCaption绑定添加到data-bind:

<select data-bind="options: availableCountries,optionsText: 'countryName',optionsCaption: 'Select...'"></select>

这是工作小提琴:http://jsfiddle.net/vyshniakov/tuMta/1/

原文链接:https://www.f2er.com/js/156174.html

猜你在找的JavaScript相关文章