【问题标题】:knockoutjs how to get the selected option arrayObjectknockoutjs 如何获取选中的选项arrayObject
【发布时间】:2013-02-05 11:45:14
【问题描述】:

我要获取选中的选项对象

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

【问题讨论】:

标签: knockout.js knockout-2.0


【解决方案1】:

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

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

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

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

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

【讨论】:

  • console.log(data) // 只转储所选值的字符串,我想关联数据数组
  • 它不只返回一个字符串,它返回数组的选定元素(即 Object { countryName= "UK", countryPopulation=65000000})。
  • 由于 optionsValue:'name',您在 selectedCountery 中只得到一个字符串。从绑定中删除它。
猜你喜欢
  • 1970-01-01
  • 2012-09-25
  • 2012-05-19
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
相关资源
最近更新 更多