我在选择列表中使用knockout options binding和select2 plugin。最初我不想在默认情况下选择任何选项,而是希望显示类似“选择国家...”的文本,并且最初应选择此文本。为此,我使用了淘汰赛optionsCaption binding
。它工作正常,但如果我在选择列表上应用select2插件,则不会选择初始默认文本。这是我的代码:
HTML
<select data-bind="options: array, optionsCaption: 'All'" size="1">
</select>
JS
$('select').select2();
function VM(){
this.array =
['Afghanostan', 'Albania', 'Algeria', 'Argentina'];
}
ko.applyBindings(new VM());
我也创建了JSFIDDLE。
如何解决这个问题?
答案 0 :(得分:1)
试试此代码
$('select').select2({
placeholder: "ALL"
});
<select data-bind="options: array" size="1" style="width: 200px;">
<option><option>
</select>
答案 1 :(得分:0)
这与“All”的值为“”有关。来自select2的来源:
initSelection: function () {
var selected;
if (this.opts.element.val() === "") {
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
}
});
}
}
如您所见,如果element.val()==='',它会短路。您需要修改select2的源以使用空值选项。