【问题标题】:Knockoutjs select initial value bindingKnockoutjs 选择初始值绑定
【发布时间】:2012-10-09 17:05:35
【问题描述】:

我有以下 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>

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    您的 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>​
    

    Fiddle

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

    value: selectedCountry

    【讨论】:

      猜你喜欢
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 2011-10-02
      • 2019-09-13
      相关资源
      最近更新 更多