2012-11-26 244 views
2

我的問題很簡單,但我沒有找到一個明確的例子。 我想爲選擇添加optgroup,並用jquery填充選項,因爲它不起作用。 這是我的代碼:添加選項組與jQuery選擇

$('#ptype').change(function() { 
     $.post(
        "/sell/site/index/categories", 
        { 
         'parent_id': $('#ptype').val() 
        }, 
        function(response){ 
         var categories = $.parseJSON(response); 

         $('#sub_category').empty(); 
         $.each(categories, function (index) { 

          var optgroup = $('<optgroup/>'); 

          $.each(this.children, function (index) { 
           optgroup.add($("<option></option>") 
              .attr("value",index) 
              .text(this)); 
          }); 

          $("#sub_category").append(optgroup); 

         }); 

         $("#sub_category").multiselect('refresh'); //refresh the select here 
        } 
       ); 
     }); 

任何幫助將不勝感激! 謝謝!的

$.each(this.children, function (index) { 

this

+0

你不應該需要調用'$ .parseJSON()' - 設置''json''一個'dataType'和jQuery會自動解析它,並將結果傳遞到您的回電話。如果你沒有明確地設置數據類型,jQuery會根據響應進行智能猜測,所以它可能仍然會嘗試爲你解析它,在這種情況下,你嘗試再次使用'$ .parseJSON()'解析它將不會工作。 – nnnnnn

回答

1

使用本

$.each($(this).children(), function (index) { 

代替指DOM元素本身; $(this)將元素包裝在一個jQuery對象中。

並且您不必使用parseJson ..(如果您已將響應指定爲json(dataType))。

var categories = $.parseJSON(response); 

經過這個http://api.jquery.com/jQuery.post/。你可以直接使用$ .each函數中的響應..(請確保你有你想要的格式的響應)..

+0

這是對有用的提示,我改變了我的代碼,但是,它沒有解決我的問題。 –

14

好吧,我終於找到了解決方案,但是,感謝從你們。 這裏的工作代碼:

$('#ptype').change(
      function() { 
       $.ajax({ 
        type: 'POST', 
        url: "/sell/site/index/categories", 
        data: { 'parent_id': $('#ptype').val() }, 
        success: function(data){ updateCategories(data); }, 
        dataType: 'json' 
      }) 
     } 
    ); 

function updateCategories(categories){ 
     $('#sub_category').empty(); 
     $.each(categories, function (index) { 
      var optgroup = $('<optgroup>'); 
      optgroup.attr('label',categories[index].name); 

      $.each(categories[index].children, function (i) { 
       var option = $("<option></option>"); 
       option.val(i); 
       option.text(categories[index].children[i]); 

       optgroup.append(option); 
      }); 
      $("#sub_category").append(optgroup); 

     }); 

     $("#sub_category").multiselect('refresh'); //refresh the select here 
}