我想知道有没有办法将局部变量分配给knockout变量?
例如说视图模型是:
var index = $("#country :selected").text();
var viewmodel = {
CountriesList : ko.observableArray([]),
CountryId: ko.observable(),
Text: ko.observable(index)
}
查看是:
<select id="country" data-bind="options: $parent.CountriesList ,optionsText: 'CountryName',optionsValue:'CountryId',value:CountryId,optionsCaption: 'Select Country..'"
style="width: 148px">
</select>
请有人帮助我如何获得optionsText
下拉值?
我的CountriesList
是一个可观察的数组,它会获得(CountryName:'india',CountryId:'1')
*样本等值。
答案 0 :(得分:0)
这里有两个示例,您可以获得optionsText
CountryId
绑定,因此绑定value
包含适当的CountryId
CountryName
绑定,因此绑定value
包含目标CountryName
HTML
Binding on CountryId: <select id="country" data-bind="options: CountriesList ,optionsText: 'CountryName', optionsValue:'CountryId', value: CountryId, optionsCaption: 'Select Country..'"style="width: 148px"></select>
<br/>
Binding on CountryName: <select id="country" data-bind="options: CountriesList ,optionsText: 'CountryName', optionsValue:'CountryName', value: CountryName, optionsCaption: 'Select Country..'"style="width: 148px"></select>
的JavaScript
var countries = [
{ "CountryName": "India1", "CountryId": "1" },
{ "CountryName": "India2", "CountryId": "2" },
{ "CountryName": "India3", "CountryId": "3" }
];
var ViewModel = function(){
var self = this;
self.CountriesList = ko.observableArray(countries);
self.CountryId = ko.observable();
self.CountryName = ko.observable();
self.CountryId.subscribe(function(newValue) {
if(newValue){
var index = newValue - 1; //because "Select Country.." is the first item
alert(countries[index].CountryName);
}
}, this);
self.CountryName.subscribe(function(newValue) {
if(newValue){
alert(newValue);
}
}, this);
};
ko.applyBindings(new ViewModel);
您可以使用代码here