Knockout.js knockoutjs如何获取所选选项arrayObject
我想获取选定的选项对象Knockout.js knockoutjs如何获取所选选项arrayObject,knockout.js,knockout-2.0,Knockout.js,Knockout 2.0,我想获取选定的选项对象 <select data-bind="options: availableCountries, value: selectedCountry, event: { select: onSelect}"></select> <script type="text/javascript"> // Constructor for an object with two propert
<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>
//具有两个属性的对象的构造函数
变量国家=功能(名称、人口){
this.countryName=名称;
this.countryPopulation=人口;
};
var viewModel={
可用国家/地区:韩国([
新国家(“英国”,65000000),
新国家(“美国”,32000000),
新国家(“瑞典”,29000000)
]),
selectedCountry:ko.observable(),//默认情况下未选择任何内容
onSelect:function(){
console.log(viewModel.selectedCountry)
//它只显示了一个国家的名称和我所看到的整个对象
//例如,{“UK”,65000000}//在所选框中选择该选项
}
};
您不必将select事件添加到控件中。更有效的方法是订阅selectedCountry
更改:
viewModel.selectedCountry.subscribe(function (data) {
console.log(data)
});
如果您不希望在默认情况下选择任何国家/地区,则必须将选项caption
绑定添加到数据绑定
:
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Select...'"></select>
这里是工作提琴:您能在JSFIDLE中发布您的真实代码吗?因为您显示的内容应该可以正常工作,请参见:只需删除
选项value:'name'
,它就可以正常工作:谢谢@nemesv,但它会在数据绑定控制台时产生问题。log(data)//只转储选定值的字符串,我希望关联数据数组。它不仅返回字符串,还返回数组的选定元素(即对象{countryName=“UK”,countryPopulation=65000000})。由于选项value:'name',您在selecetedCountery中只得到一个字符串。请将其从绑定中删除。