2015-10-25 123 views
0

我使用select2.js庫下面的代碼,我想有從選項標籤的所有類的選擇2列表,像<li class="active select2-selection__choice" title="AA"><span ...獲取類slect2.js標籤

<select id="example" multiple="multiple" style="width:100%"> 
<option value="AA" class="active" selected>AA</option> 
<option value="BB" class="stanby" selected>BB</option> 
<option value="CC"class="active" selected>CC</option> 

$("#example").select2(); 

Here是合作的小提琴。

enter image description here

回答

1

這可以通過提供一個自定義的選項selectionAdapter來實現。我根據MultipleSelection的Select2實現創建了一個。

// create our custom selection adapter by extending the select2 default one 
$.fn.select2.amd.define('select2-ClassPreservingMultipleSelection',[ 
    'jquery', 
    'select2/selection/multiple', 
    'select2/utils' 
], function ($, MultipleSelection, Utils) { 
    function ClassPreservingMultipleSelection ($element, options) { 
     ClassPreservingMultipleSelection.__super__.constructor.apply(this, arguments); 
    } 

    Utils.Extend(ClassPreservingMultipleSelection, MultipleSelection); 

    // this function was changed to propagate the `selection` argument 
    ClassPreservingMultipleSelection.prototype.selectionContainer = function (selection) { 
     var $baseContainer = ClassPreservingMultipleSelection.__super__.selectionContainer.apply(this, arguments); 

     // this line is what actually adds your CSS-classes 
     return $baseContainer.addClass(selection.element.className); 
    }; 

    // this is a copy-paste of the base method with only one line changed 
    ClassPreservingMultipleSelection.prototype.update = function (data) { 
     this.clear(); 

     if (data.length === 0) { 
      return; 
     } 

     var $selections = []; 

     for (var d = 0; d < data.length; d++) { 
      var selection = data[d]; 

      // This is the only changed line in this method - we added the 'selection' propagation 
      var $selection = this.selectionContainer(selection); 
      var formatted = this.display(selection, $selection); 

      $selection.append(formatted); 
      $selection.prop('title', selection.title || selection.text); 

      $selection.data('data', selection); 

      $selections.push($selection); 
     } 

     var $rendered = this.$selection.find('.select2-selection__rendered'); 

     Utils.appendMany($rendered, $selections); 
     console.log($rendered.html()); 
    }; 

    return ClassPreservingMultipleSelection; 
}); 

$("#example").select2({ 
    selectionAdapter: $.fn.select2.amd.require('select2-ClassPreservingMultipleSelection') 
}); 

這是您的updated JsFiddle

+0

很多工作對於這樣一個小事情,但這正是我想要實現的,非常感謝@Dhahariel –