0

我最近将 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问题。请帮我提供解决方法。

4

1 回答 1

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 -->

于 2015-08-13T10:47:04.307 回答