2

我的问题很简单,但我没有找到一个明确的例子。我正在尝试为选择添加 optgroup 并使用 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
                    }
                );
        });

任何帮助将不胜感激!谢谢!

4

2 回答 2

18

好的,所以我最终自己想出了解决方案,但是,感谢你们提供的有用提示。这是工作代码:

$('#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
}
于 2012-11-26T15:33:20.553 回答
1

use this

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

instead of

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

this refers to the DOM element itself; $(this) wraps the element up in a jQuery object.

and you don't have to use parseJson..(if u have specified the response as json (dataType)).

var categories = $.parseJSON(response);

go through this http://api.jquery.com/jQuery.post/. u can directly use response in $.each function .. (make sure u have responce in the format u wanted)..

于 2012-11-26T11:05:45.367 回答