Knockout.js如何获取选定的选项arrayObject [英] knockoutjs how to get the selected option arrayObject

查看:67
本文介绍了Knockout.js如何获取选定的选项arrayObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要获取选定的选项对象

I want to get the selected option object

    <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>

推荐答案

您不必向控件中添加选择事件.更有效的方法是订阅selectedCountry更改:

You don't have to add select event to the control. More efficient way is to subscribe on selectedCountry changes:

viewModel.selectedCountry.subscribe(function (data) {
        console.log(data)
    });

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

If you don't want any country is selected by default you have to add optionsCaption binding to the data-bind:

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

这里正在工作: http://jsfiddle.net/vyshniakov/tuMta/1/

这篇关于Knockout.js如何获取选定的选项arrayObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆