2013-03-23 92 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/

哪一个您使用取决于您需要的关于所选类别的信息。