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/

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...