1

我正在尝试在 KO 的绑定中使用嵌套的options, ( optionsText, optionsValue) 和value绑定。foreach

我希望以下代码将选择框绑定到 ViewModel 的相关项Item,但它似乎没有更新视图模型中的值——它们始终保持为我用“n/a”初始化它们的值——我该怎么做那?

我已经设置了一个html页面,如下所示:

<table>
    <tbody data-bind="foreach: Items">
        <tr>
            <td>
                <select data-bind="options: $parent.Countries, optionsText: 'Name', optionsValue: 'Code', value: 'Country'"></select>
            </td>
            <td>
                <span data-bind="text: Country"></span>                    
            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2">
                <a href="#" data-bind="click: AddItem">Add item</a>
            </td>
        </tr>
    </tfoot>
</table>

使用以下 JavaScript:

var countries = ko.observableArray([
    { Name : "United Kingdom", Code : "UK", Population : "1 Monarch" },
    { Name : "Australia", Code : "AU", Population : "22 million kangaroos" },
    { Name : "Antarctica", Code : "AQ", Population : "100,000 penguins (0 polar bears)" }
]);

var item = { Country : "n/a" };

var ViewModel = function() {
    this.Countries = countries;

    this.Items = ko.observableArray();
    this.AddItem = function() {
        this.Items.push(ko.mapping.fromJS(item));
    };
};
var vm = new ViewModel();

ko.applyBindings(vm);

小提琴在这里

4

1 回答 1

2

value绑定中删除引号:

<select data-bind="options: $parent.Countries, 
                   optionsText: 'Name', 
                   optionsValue: 'Code', 
                   value: Country"></select>

这是工作小提琴: 链接

于 2012-09-04T07:19:02.913 回答