bootstrap-multiselect.js如何動態更新select裏的數據

在使用jQuery的bootstrap-multiselect插件時可能會遇到一個問題javascript

就是想要動態的去更新select裏的數據html

 

好比咱們要使一個id=select的選擇框實現多選java

那麼先用ajax得到新數據後清空select再一個個拼成optionajax

 

[javascript]  view plain  copy
 
  1. $("#select").html("");  
  2. for (var i = 0; i < json.length; i++) {  
  3.     $("#select").append("<option value='" + json[i].code + "'>" + json[i].name + "</option>");  
  4. }  

 

這時再從新調用一次multiselect()或使用multiselect("refresh")可能並無任何效果json

正確的姿式應該是先使用destroy破壞multiselect以後再從新構建bootstrap

 

[javascript]  view plain  copy
 
  1. $("#select").multiselect("destroy").multiselect({  
  2.     // 自定義參數,按本身需求定義  
  3.     nonSelectedText : '--請選擇--',   
  4.     maxHeight : 350,   
  5.     includeSelectAllOption : true,   
  6.     numberDisplayed : 5  
  7. });  

 

最後代碼以下app

 

[javascript]  view plain  copy
 
  1. function refreshMultiSelect() {  
  2.     $.ajax({  
  3.         type : "POST",  
  4.         url : url,  
  5.         data : data,  
  6.         dataType : "json",  
  7.         success : function(json) {  
  8.             $("#select").html("");  
  9.             for (var i = 0; i < json.length; i++) {  
  10.                 $("#select").append("<option value='" + json[i].code + "'>" + json[i].name + "</option>");  
  11.             }  
  12.             $("#select").multiselect("destroy").multiselect({  
  13.                 // 自定義參數,按本身需求定義  
  14.                 nonSelectedText : '--請選擇--',   
  15.                 maxHeight : 350,   
  16.                 includeSelectAllOption : true,   
  17.                 numberDisplayed : 5  
  18.             });  
  19.         }  
  20.     });  
  21. }  
相關文章
相關標籤/搜索