2

私の質問は簡単ですが、それを行う明確な例は見つかりませんでした。select に 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

これを使って

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

それ以外の

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

thisDOM要素自体を指します。$(this)要素をjQueryオブジェクトにラップします。

parseJsonを使用する必要はありません(uが応答をjson(dataType)として指定した場合)。

var categories = $.parseJSON(response);

このhttp://api.jquery.com/jQuery.post/に目を通します。uは$.each関数で応答を直接使用できます..(uが希望する形式で応答していることを確認してください)。

于 2012-11-26T11:05:45.367 に答える