Skip to main content
 首页 » 编程设计

jquery之在 select with optgroup 中使用 selectedOptions Knockout 绑定(bind)来预选择多个值

2026年05月17日37arxive

埃洛,

我已经尝试了使用 optgropus 制作(多个)选择框的所有选项,并将选项/selectedOptions 与 knockout 绑定(bind)。

selectedOptions 绑定(bind)似乎存在问题。我的数据似乎是合法的,但它只是不会显示预选的选项。

我在 JSFiddle 中做了一个例子:http://jsfiddle.net/aCS7D/251/

<select data-bind="selectedOptions: selectedOptions" multiple="multiple"> 
<option>Please choose an option</option> 
<optgroup data-bind="repeat: groups" data-repeat-bind="attr: {label: $item().label}"> 
    <option data-bind="repeat: $item().children" data-repeat-bind="text: $item().label, option: $item()"></option> 
</optgroup> 

对于单个选定选项,它可以工作,但对于多个选定选项,选择框无法正确呈现它们。

如果有人能解决这个问题,你将成为我的英雄!

请您参考如下方法:

您可以在应用 this 等绑定(bind)后推送它们:

this.selectedOptions = ko.observableArray([]); 
 
//The single selected option 
this.selectedOption = ko.observable(selected1);     
 
var vm = new ViewModel() 
ko.applyBindings(vm); 
var selected1 = vm.groups()[1].children()[1]; 
var selected2 = vm.groups()[1].children()[0]; 
vm.selectedOptions.push(selected1); 
vm.selectedOptions.push(selected2);