2

我有以下 knockoutjs 代码。问题是我希望能够设置 selectedCountry 变量的值,但要做到这一点,我必须将其绑定到 select 元素作为 selectedCountry,但是为了获得初始值,我必须使用这个 selectedCountry() 代替, and am thus not able to update the value of selectedCountry when another option is selected. 我该怎么做?

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>
4

1 回答 1

0

您的selectedCountry财产拥有当前选定的人口而不是全部 country

因此,在您拥有的任何地方,您都selectedCountry().countryPopulation应该简单地写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>​

小提琴

()请注意,您selectvalue绑定中有一组额外的,因此正确的语法是:

value: selectedCountry

于 2012-10-19T06:18:03.463 回答