2017-04-13 83 views
0

我創建了select2下拉菜單。現在,我想在此下拉菜單中按國名添加說明,城市,商店等。 如何添加國家城市名稱,地區,商店等?Select2顯示更多值

(function($) { 
     $(function() { 
      var isoCountries = [ 
       { id: 'QA', text: 'Qatar',}, 
       { id: 'CA', text: 'Canada'}, 
       { id: 'CN', text: 'China'}, 
       { id: 'DE', text: 'Germany'}, 
       { id: 'RU', text: 'Russia'}, 
       { id: 'IT', text: 'Italy'} 
      ]; 

      $("[name='market']").select2({ 
       placeholder: "Select a country", 
       data: isoCountries 
      }); 
     }); 
    })(jQuery); 

enter image description here

+0

https://select2.github.io/examples.html#data-ajax 使用此選項,編輯選擇2的查看HTML: 'formatSelection:功能(項目){ 回報item.text +' '+ item.xxx; //一些其他屬性 }' – lakshay

+0

請參閱示例頁面源代碼(Ctrl + U)以查看額外數據顯示在html中的select2 – lakshay

回答

0

檢查下面的代碼:

(function($) { 
 
    var isoCountries = [ 
 
     { id: 'US', text: 'USA', description: 'New York'}, 
 
     { id: 'SP', text: 'Spain', description: 'Barcelona'} 
 
    ]; 
 

 
    $("[name='market']").select2({ 
 
     placeholder: "Select a country", 
 
     data: isoCountries, 
 
     templateResult: function(data){ 
 
      return $('<span>') 
 
      .html(data.text + ' - ') 
 
      .append($('<i>') 
 
      .html(data.description)); 
 
     }, 
 
     templateSelection: function(data){ 
 
      return $('<span>') 
 
      .html(data.text + ' - ') 
 
      .append($('<i>') 
 
      .html(data.description)); 
 
     } 
 
    }); 
 
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> 
 
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/> 
 

 
<select name="market" style="width:100%;"></select>

它僅適用於選擇2 4.0以上的版本。如果您想使用它與以前的版本,而不是usisng templateResult和templateSelection使用formatResult和formatSelection。