我最近将select2 3.5.1升级为select2 4.0。
请在下面找到代码段。
var self = this,
$view = $(view);
$.fn.select2.amd.require(['select2/data/array', 'select2/utils'], function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
callback({
results: [{
id: 1,
text: "Friesd"
}, {
id: 2,
text: "Ham"
}, {
id: 3,
text: "Eggs Benedict"
}]
});
}
$view.select2({
// templateSelection: ko.unwrap(self.formatFunc),
// templateResult: ko.unwrap(self.formatFunc),
placeholderOption: 'first',
allowClear: false,
multiple: "multiple",
placeholder: 'search..',
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
dropdownParent: $('.container')),
dataAdapter: CustomData,
//id: ko.unwrap(self.idFunc)
});
它成功显示结果,但选项无法点击。我真的怀疑它可能是一个CSS问题。请帮我解决。
先谢谢。
答案 0 :(得分:1)
如果你正在使用Knockout,正如你的标签所示,你的设置应该在一个自定义绑定处理程序中完成(这是你的多选需求):
ko.bindingHandlers.select2 = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
ko.bindingHandlers.options.init(element, valueAccessor, allBindingsAccessor, data, context);
$(element).select2({
// templateSelection: ko.unwrap(self.formatFunc),
// templateResult: ko.unwrap(self.formatFunc),
placeholderOption: 'first',
allowClear: false,
multiple: "multiple",
placeholder: 'search..',
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
//id: ko.unwrap(self.idFunc)
});
},
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
ko.bindingHandlers.options.update(element, valueAccessor, allBindingsAccessor, data, context);
}
};
ko.applyBindings({
fruit: ['apple', 'orange', 'banana', 'tomato'],
myFruit: ko.observableArray()
});
select {
min-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<select data-bind="select2:true, options:fruit, optionsCaption:'pick a fruit', selectedOptions:myFruit"></select>
<br />chose:
<!-- ko text:myFruit().join(',') -->
<!-- /ko -->