Javascript 如何将局部值指定给敲除可观察对象

Javascript 如何将局部值指定给敲除可观察对象,javascript,knockout.js,Javascript,Knockout.js,我想知道是否有一种方法可以将局部变量分配给敲除变量 例如,假设视图模型为: var index = $("#country :selected").text(); var viewmodel = { CountriesList : ko.observableArray([]), CountryId: ko.observable(), Text: ko.observable(index) } 视图为: <select id="country" dat

我想知道是否有一种方法可以将局部变量分配给敲除变量

例如,假设视图模型为:

 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>

请有人帮助我如何获得下拉值的
选项text

My
CountriesList
是一个可观察的数组,它将获得如下值:
(CountryName:'india',CountryId:'1')
*示例。

以下是两个示例,您可以如何获得
选项文本

  • 绑定在
    CountryId
    上,因此绑定
    value
    包含适当的
    CountryId
  • 绑定在
    CountryName
    上,因此绑定
    value
    包含目标
    CountryName
  • Html


    你可以玩代码

    你正在向后看-你需要创建一个带有初始值的视图模型,然后将其绑定到UI。请注意,我对ko不太了解。你能详细说明一下吗?这里有一些非常好的教程,它们将从一开始就指导你,并且有很多代码示例。很高兴了解一些基本知识。我读了很多遍,其中的例子并没有给我任何关于如何实现上述目标的想法…可能是重复的
    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>
    
    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);