2017-04-20 80 views
1

我有類似的問題thisthis one。我已經嘗試了評論中描述的所有解決方案。並達到了某種程度上的作品。使用AJAX加載引導程序選擇選擇器

我的問題是,當我從#main_cat中選擇一個選項時,第一次加載.sub_cat的內容(AJAX加載正確)。但是,如果我從#main_cat中選擇另一個選項,則會加載內容,但不會使用選擇器選擇器樣式。這只是表明:

glyphicon-sort-by-alphabetOPTION 1(如下截圖)

HTML

<select id="main_cat" name="main_cat" class="selectpicker"> 
    <option selected="-1">Kies een thema</option> 
    <option value="Actief_Avontuur" data-name="Actie & avontuur" data-icon="glyphicon-sort-by-alphabet" class="special">&nbsp;&nbsp;Actief, sportief en avontuurlijk</option> 
    <option value="Creatief" data-name="Creatief" data-icon="glyphicon-sort-by-alphabet-alt" class="special">&nbsp;&nbsp;Creatief</option> 
</select> 
<select name="sub_cat" disabled="disabled" class="selectpicker_1 sub_cat"> 

jQuery的

$(function(){ 
    $('#main_cat').change(function(){ 
     var $option = $(this).find('option:selected'), 
      id = $option.val(), 
      name = $option.data('name'); 
      // open your browser's console log and ensure that you get the correct values 
     console.log(id, name); 
      $(".sub_cat").empty(); 
      // call ajax 
     $.ajax({ 
      url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",  
      type:'POST', 
      data: { 
       action: 'my_special_ajax_call', 
       main_catid: id, 
       main_name: name 
      }, 
      success: function (results) { 
       $(".sub_cat").removeAttr('disabled').html(results); 
       $('.selectpicker_1').selectpicker(["refresh"]); 
      } 
     }); 
    }); 
});   

我曾經嘗試都selectpickers使用清爽:

$('.selectpicker').selectpicker(["refresh"]); 
$('.selectpicker_1').selectpicker(["refresh"]); 

這(如在鏈接的問題建議)

$('.selectpicker').selectpicker({}); 

下面是一些截圖:第一個是當我選擇的第一次和第二個選項是,當我選擇從其他選項#main_cat。我是否必須用foreach做些事情,以便在AJAX完成時不斷重新加載?有人知道解決方案嗎?

選擇首次 Selecting an option for the first time

的選項中選擇一個選項,第二次 Selecting an option for the second time

+0

'$ selectpicker([ 「刷新」]);( 'selectpicker。')。 $('。selectpicker_1')。selectpicker([「refresh」]);'remove'[',']'方括號'$('。selectpicker')。selectpicker(「refresh」); ('。selectpicker_1')。selectpicker(「refresh」);'如果仍然無法正常工作,請檢查控制檯是否有任何錯誤? – Curiousdev

+1

有趣的是,我不記得使用'[',']',但我刪除了它們,但它沒有解決問題。並檢查控制檯,什麼都沒有。 –

+0

在'success'函數中加入了一個調試嗎? – Curiousdev

回答

1

我用這樣的:

$.ajax({ 
    url: "yoururl", 
    type: 'post', 
    data: {data: data}, 
    success: function(response){ 
      target.empty(); 
      target.html(response); 
      target.selectpicker('refresh'); // without the [] 
    } 
}); 

注意,我清空選擇,在響應和令人耳目一新之後......它工作的很好! :d 希望這有助於...

1

您需要添加以下內容:

.done(function (msg) { 
    $("#models_dropdown").html(msg).selectpicker('refresh'); 
});