使用Knockout.js根据组合框选择生成表格内容

时间:2013-05-27 11:36:53

标签: javascript html json knockout.js

我想要一个组合框按钮(由Knockout JS控制)定义了 HTML表的内容。我试图在jsfiddle中构建它 不成功。

HTML:

<br>Groups:
<br>
<select data-bind="value: selectedFruitGroupId,
                   options: groups,
                   optionsText: 'name'"></select>
<br>
<br>Fruits Group:</br>
<table border="1">
    <thead>
        <tr>
            <th>Fruit</th>
            <th>Weight</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: selectedFruitsGroup">
        <tr>
            <td data-bind="text: name"></td>
            <td data-bind="text: weight"></td>
        </tr>
    </tbody>
</table>

使用Javascript:

ViewModel = function() {
    this.selectedFruitGroupId = ko.observable();

    this.groups = [
        {name:"A", id:0},
        {name:"B", id:1},
        {name:"C", id:2}
    ];

    this.fruitsGroups = [
        {
            id: 0,
            fruits: [
                { name: 'Apple', weight: '80' },
                { name: 'Orange', weight: '100' },
                { name: 'Banana', weight: '140' }
            ]
        }, 
        {
            id: 1,
            fruits: [
                { name: 'Pear', weight: '80' },
                { name: 'Melon', weight: '100' },
                { name: 'Grapes', weight: '140' }
            ]
        }, 
        {
            id: 2,
            fruits: [
                { name: 'Mango', weight: '80' },
                { name: 'Kiwi', weight: '100' },
                { name: 'Coconut', weight: '140' }
            ]
        }
    ];

    this.selectedFruitsGroup = ko.computed(function() {
        return ko.utils.arrayFilter(this.fruitsGroups, function(fruitGroup) {
            return fruitGroup.id == this.selectedFruitGroupId();
        })[0];
    });
}

然后,我想在选择“A”时,会显示“Apple”,“Orange”和“Banana”。 当选择“B”时,显示“梨”,“甜瓜”和“葡萄”。当选择“C”时,它显示“Mango”,“Kiwi”和“Coconut”。

非常好的问候。

1 个答案:

答案 0 :(得分:4)

在select元素中使用optionsvalue绑定并将其设置为id

<select data-bind="value: selectedFruitGroupId,
               options: groups,
               optionsText: 'name', 
               optionsValue: 'id'"></select>

这是一个有效的更新小提琴:http://jsfiddle.net/QmF9V/3/