2013-03-23 80 views
3

我有以下的下拉菜單:預選項目與淘汰賽

<div> 
    Dummy 
    <select data-bind="options: categories, optionsText: 'description', value: 2"></select> 
</div> 

下面的JavaScript:

function ViewModel() 
{ 

    this.categories = ko.observableArray([ 
      new Category(1, "Non classé"), 
      new Category(2, "Non nucléaire"), 
      new Category(3, "Classe II irradié"), 
      new Category(4, "Classe III") 
    ]); 

    // Constructor for an object with two properties 
    function Category(id, description) { 
     this.id = id; 
     this.description = description; 
    }; 
} 

ko.applyBindings(new ViewModel()); 

我想用2號預選擇元素在下拉菜單中。

任何想法?

謝謝。

的jsfiddle:http://jsfiddle.net/RfWVP/276/我能想到的

回答

5

兩種方法可以做到這一點。無論哪種方式,你必須添加一個selectedCategory observable屬性來存儲跟蹤當前選擇的選項。

  1. 使用optionsValue綁定並指定'id'的屬性,您想爲每個optionvalue使用方法:

    <select data-bind="options: categories, 
            optionsText: 'description', 
            value: selectedCategory, 
            optionsValue: 'id'">     
    </select> 
    

    然後設置selectedCategory等於 「2」:

    this.selectedCategory = ko.observable(2); 
    

    例如:http://jsfiddle.net/RfWVP/281/

  2. 創建類別的可觀察到的陣列之前,創建具有ID 「2」 的類別,並設置selectedCategory等於類別:

    var selected = new Category(2, "Non nucléaire"); 
    
    this.categories = ko.observableArray([ 
        new Category(1, "Non classé"), 
        selected, 
        new Category(3, "Classe II irradié"), 
        new Category(4, "Classe III") 
    ]); 
    
    this.selectedCategory = ko.observable(selected); 
    

    實施例:http://jsfiddle.net/RfWVP/280/

哪一個您使用取決於您需要的關於所選類別的信息。