添加带有选项的 optgroup 以使用 jQuery 进行选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13563399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:44:45  来源:igfitidea点击:

Add optgroup with options to select with jQuery

jqueryselectoptgroup

提问by Baseem Najjar

my question is simple but yet I didn't find a clear example of doing that. I'm trying to add optgroup for a select and fill it with options using jquery for some reason it's not working. this is my code:

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

Any help would be greatly appreciated! Thanks!

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

回答by Baseem Najjar

Ok so I figured out the solution myself in the end, however, thanks for the useful tips from you guys. here's the working code:

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

$('#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
}

回答by bipen

use this

用这个

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

instead of

代替

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

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

this指的是 DOM 元素本身;$(this)将元素包装在一个 jQuery 对象中。

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

并且您不必使用 parseJson ..(如果您已将响应指定为 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)..

通过这个http://api.jquery.com/jQuery.post/。你可以直接在 $.each 函数中使用 response ..(确保你有你想要的格式的响应)。