【问题标题】:Incorrect combobox binding with Knockout framework与 Knockout 框架的组合框绑定不正确
【发布时间】:2012-05-27 09:28:40
【问题描述】:

大家好

我用表格创建了简单的页面,并希望使用敲除框架用数据填充它。

该表包含三列,显示来自底层 viewModel 的数据。 通常这是可行的,但我对第一列(允许选择当前项目的组合框)有一点问题:我想将“数字”属性显示为组合标题并在绑定中指定属性名称,但显示值“[对象对象]”代替number 属性。

那么,我的绑定有什么问题。如何正确显示“数字”属性?

谢谢。

页面代码在这里:

<head>
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js" type="text/javascript"></script>
</head>
<body>
<button data-bind="click: addItem">Add product</button>

    <table>
        <thead>
            <tr>
                <th>Number</th>
                <th>Name</th>
                <th>Count</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: itemsData">
            <tr>
                <td>
                    <select data-bind="options: $root.avaliableItems, optionsText: $data.number, optionsCaption: 'Select...', value: tableItem"> </select>
                </td>
                <td data-bind="with: tableItem">
                    <span data-bind="text: name"> </span>
                </td>
                <td>
                    <input data-bind="value: count" />
                </td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        function TableItem(number, name){
            var self = this;
            self.number = ko.observable(number);
            self.name = ko.observable(name);
        };

        function ExtendedItem(){
            var self = this;
            self.tableItem = ko.observable();
            self.count = ko.observable(1);
        };

        function SampleViewModel(){
            var self = this;
            self.avaliableItems = [
                new TableItem("Num1", "Item 1 name"),
                new TableItem("Num2", "Item 2 name"),
                new TableItem("Num3", "Item 3 name"),
                new TableItem("Num4", "Item 4 name"),
                new TableItem("Num5", "Item 5 name"),
                new TableItem("Num6", "Item 6 name"),
                new TableItem("Num7", "Item 7 name")
            ];

            self.itemsData = ko.observableArray();

            self.addItem = function(){
                self.itemsData.push(new ExtendedItem());
            };
        };
        ko.applyBindings(new SampleViewModel());
    </script>
</body>

【问题讨论】:

    标签: javascript binding knockout.js


    【解决方案1】:

    您的选择应如下所示:

    <select data-bind="options: $root.avaliableItems, optionsText: 'number', optionsCaption: 'Select...', value: tableItem"> </select>
    

    注意optionsText 的使用,它接受一个字符串(标识属性名称)。

    这是一个演示:http://jsfiddle.net/jearles/5qakM/

    阅读the options binding docs了解更多详情。

    【讨论】:

    • 约翰,非常感谢。那行得通。我确实尝试过较早的设置值“数字”,但没有引号“'”并且没有引号绑定不起作用))当时;我添加引号和绑定完美)
    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2013-06-20
    • 2023-03-28
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    相关资源
    最近更新 更多