我有以下下拉列表:
<div>
Dummy
<select data-bind="options: categories, optionsText: 'description', value: 2"></select>
</div>
Run Code Online (Sandbox Code Playgroud)
使用以下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());
Run Code Online (Sandbox Code Playgroud)
我想在下拉列表中预先选择id为2的元素.
任何的想法?
谢谢.
jsFiddle:http://jsfiddle.net/RfWVP/276/
我可以想到两种方法来做到这一点.无论哪种方式,您都必须添加一个selectedCategory可观察的属性来存储跟踪当前选定的选项.
使用optionsValue绑定和指定'id'的属性,您想为使用value每个option:
<select data-bind="options: categories,
optionsText: 'description',
value: selectedCategory,
optionsValue: 'id'">
</select>
Run Code Online (Sandbox Code Playgroud)
然后设置selectedCategory等于"2":
this.selectedCategory = ko.observable(2);
Run Code Online (Sandbox Code Playgroud)
在创建可观察的类别数组之前创建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);
Run Code Online (Sandbox Code Playgroud)
您使用哪一个取决于您对所选类别所需的信息.