【问题标题】:Use Knockout.js to generate table content according to the combobox choose使用 Knockout.js 根据组合框选择生成表格内容
【发布时间】:2013-05-22 06:15:57
【问题描述】:

我想要一个组合框按钮(由 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];
    });
}

Then, I would like that when choosed "A", it is showed "Apple", "Orange" and "Banana". 选择“B”时,显示“梨”、“甜瓜”和“葡萄”。选择“C”时,显示“Mango”、“Kiwi”和“Coconut”。

非常好的问候。

【问题讨论】:

    标签: javascript html json knockout.js


    【解决方案1】:

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

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

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

    【讨论】:

    • @ragnarok56 我看到了你的代码,如果它的列数是动态的呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2019-09-18
    • 2011-07-06
    • 2017-04-21
    • 2021-06-19
    • 2013-09-14
    相关资源
    最近更新 更多