如何在select2选择框中显示我选择的图标?

时间:2017-06-16 14:44:52

标签: icons jquery-select2

当我选择一个图标时,只有文本显示在我的选择框中,而不是图标:

$(document).ready(function(){
  $("#social").select2({
   templateResult: formatState
  });
 });
 
 function formatState (state) {
  if (!state.id) { return state.text; }
  var $state = $(
   '<span ><i class="fa fa-'+ state.id +'"> ' + state.text + '</span>'
  );
  return $state;
 }
<link href="https://adminlte.io/themes/AdminLTE/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://adminlte.io/themes/AdminLTE/plugins/select2/select2.min.css" rel="stylesheet"/>
<link href="https://adminlte.io/themes/AdminLTE/dist/css/AdminLTE.min.css" rel="stylesheet"/>
<script src="https://adminlte.io/themes/AdminLTE/plugins/jQuery/jquery-3.1.1.min.js"></script>
 <script src="https://adminlte.io/themes/AdminLTE/bootstrap/js/bootstrap.min.js"></script>
 <script src="https://adminlte.io/themes/AdminLTE/plugins/select2/select2.full.min.js"></script>



<select id='social' style='width: 200px;'>
 <option value='facebook'>Facebook</option>
 <option value='twitter'>Twitter</option>
 <option value='linkedin'>Linkedin</option>
 <option value='google'>Google</option>
 <option value='vimeo'>Vimeo</option>
</select>

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(document).ready(function(){
  $("#social").select2({
   templateResult: formatState,
   templateSelection: formatState
  });
 });
 
 function formatState (state) {
  if (!state.id) { return state.text; }
  var $state = $(
   '<span ><i class="fa fa-'+ state.id +'"> ' + state.text + '</span>'
  );
  return $state;
 }
&#13;
<link href="https://adminlte.io/themes/AdminLTE/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://adminlte.io/themes/AdminLTE/plugins/select2/select2.min.css" rel="stylesheet"/>
<link href="https://adminlte.io/themes/AdminLTE/dist/css/AdminLTE.min.css" rel="stylesheet"/>
<script src="https://adminlte.io/themes/AdminLTE/plugins/jQuery/jquery-3.1.1.min.js"></script>
 <script src="https://adminlte.io/themes/AdminLTE/bootstrap/js/bootstrap.min.js"></script>
 <script src="https://adminlte.io/themes/AdminLTE/plugins/select2/select2.full.min.js"></script>



<select id='social' style='width: 200px;'>
 <option value='facebook'>Facebook</option>
 <option value='twitter'>Twitter</option>
 <option value='linkedin'>Linkedin</option>
 <option value='google'>Google</option>
 <option value='vimeo'>Vimeo</option>
</select>
&#13;
&#13;
&#13;