gpt4 book ai didi

knockout.js - knockoutjs 如何获取选中的选项arrayObject

转载 作者:行者123 更新时间:2023-12-04 13:20:01 27 4
gpt4 key购买 nike

我想获取选定的选项对象

    <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变化:

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

如果您不希望默认选择任何国家/地区,则必须添加 optionsCaption绑定(bind)到 data-bind :
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Select...'"></select>

这是工作 fiddle : http://jsfiddle.net/vyshniakov/tuMta/1/

关于knockout.js - knockoutjs 如何获取选中的选项arrayObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14706784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com