2012-11-26 33 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 
}