Knockout.js Knockoutjs选择初始值绑定

Knockout.js Knockoutjs选择初始值绑定,knockout.js,Knockout.js,我有下面的knockoutjs代码。问题是,我希望能够设置selectedCountry变量的值,但要做到这一点,我必须将其作为selectedCountry绑定到select元素,但是为了获得初始值,我必须使用此selectedCountry(),因此在选择另一个选项时无法更新selectedCountry的值。我该怎么办 The code is also available here http://jsfiddle.net/xPc9J/ <!doctype html> <

我有下面的knockoutjs代码。问题是,我希望能够设置selectedCountry变量的值,但要做到这一点,我必须将其作为selectedCountry绑定到select元素,但是为了获得初始值,我必须使用此selectedCountry(),因此在选择另一个选项时无法更新selectedCountry的值。我该怎么办

The code is also available here http://jsfiddle.net/xPc9J/

<!doctype html>
<html>
<head>
<script src="knockout-2.1.0.js" type="text/javascript"></script>

</head>
<body>
<p>
    Your country: 
    <select data-bind="options: availableCountries,  optionsValue: 'countryPopulation',optionsText: 'countryName',value: selectedCountry(), optionsCaption: 'Choose...'"></select>
</p>
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
    You have chosen a country with population 
    <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>

<script type="text/javascript">
    // Constructor for an object with two properties
    var country = function(name, population) {
        this.countryName = name;
        this.countryPopulation = population;    
    };        
 var sel=new country("USA", 320000000);
    console.log(sel);
    var viewModel = {
        availableCountries : ko.observableArray([
            new country("UK", 65000000),
            new country("USA", 320000000),
            new country("Sweden", 29000000)
        ]),
        selectedCountry : ko.observable(320000000) // Nothing selected by default
    };
    console.log(viewModel.selectedCountry());
    //viewModel.selectedCountry(sel);
    ko.applyBindings(viewModel);
</script>
</body>

</html>
此处也提供了该代码http://jsfiddle.net/xPc9J/

贵国:

. 你选择了一个人口众多的国家 . //具有两个属性的对象的构造函数 变量国家=功能(名称、人口){ this.countryName=名称; this.countryPopulation=人口; }; var sel=新国家(“美国”,32000000); 控制台日志(sel); var viewModel={ 可用国家/地区:韩国([ 新国家(“英国”,65000000), 新国家(“美国”,32000000), 新国家(“瑞典”,29000000) ]), selectedCountry:ko.observable(32000000)//默认情况下未选择任何内容 }; log(viewModel.selectedCountry()); //viewModel.selectedCountry(sel); 应用绑定(视图模型);
您的
selectedCountry
属性包含当前选定的人口,而不是全部
国家/地区

因此,无论你在哪里
selectedCountry()。countryPopulation
你都应该写 只需
selectedCountry()

。
你选择了一个人口众多的国家
.
​

注意在
选择
绑定中有一组额外的
()
,因此正确的语法是:

value:selectedCountry

<span data-bind="text: selectedCountry"></span>.
<div data-bind="visible: selectedCountry">
    You have chosen a country with population 
    <span data-bind="text: selectedCountry() ? selectedCountry(): 'unknown'">
    </span>.
</div>​