2013-05-27 49 views
1

我想要一個組合框按鈕(由Knockout JS控制),它定義了HTML表格的 內容。我試圖在jsfiddle 中建立這個失敗。使用Knockout.js根據組合框生成表格內容選擇

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」,它表現出了 「蘋果」, 「橙色」 和「香蕉」。 當選擇「B」時,顯示「梨」,「甜瓜」和「葡萄」。當選擇「C」時,顯示「芒果」,「獼猴桃」和「椰子」。

非常好的問候。

回答

4

使用optionsvalue在選擇元件結合並將其設置爲ID

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

下面有一個更新的提琴的作品:http://jsfiddle.net/QmF9V/3/

+0

非常感謝ragnarok56!有效! –

+0

@ ragnarok56我看到了你的代碼,如果它的列數是動態的呢? – Rolando

相關問題