You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery插件中处理嵌套对象生成带optgroup的下拉选单?

如何基于配置生成带optgroup的Select结构

没问题,我来帮你修改这个jQuery插件,实现根据setting.select的配置生成你需要的带<optgroup>的<select>结构。

首先看一下你的配置结构:setting.select是一个数组,里面的每个元素是一个对象,对象的键对应<optgroup>的label属性,值则是该分组下的选项数组。我们只需要通过多层循环遍历这些数据,把它们拼接成对应的HTML字符串即可。

修改后的完整插件代码如下:

$.fn.TestPlugin = function( options ) {
  var setting = $.extend({
    "image" : [ "image1.jpg", "image2.jpg", "image2.jpg"],
    "select": [
      {
        "Label 1": ["opt 1", "opt 2", "opt 3"],
        "Label 2": ["opt 4", "opt 5", "opt 6", "opt 7"]
      }
    ]
  }, options );
  
  return this.each(function( index ){
    $( this ).wrap( "<div class='container' id='container-"+ (index+1) +"'></div>" );
    
    // 生成带optgroup的select
    var $select = "<select>";
    
    // 遍历select配置数组中的每个分组对象
    $.each(setting.select, function(_, groupObj) {
      // 遍历分组对象的每个键值对(键是optgroup的label,值是选项数组)
      $.each(groupObj, function(label, optionsList) {
        // 添加optgroup起始标签
        $select += `<optgroup label="${label}">`;
        // 遍历当前分组的所有选项,生成option标签
        $.each(optionsList, function(_, optionText) {
          $select += `<option>${optionText}</option>`;
        });
        // 闭合optgroup标签
        $select += "</optgroup>";
      });
    });
    
    $select += "</select>";
    $( $select ).appendTo( "#container-"+ (index+1) +"" );
  });
};

关键逻辑说明:

  • 第一层循环:遍历setting.select数组(你的配置里目前只有一个对象,但保留数组结构可以支持未来添加多组独立的optgroup集合)
  • 第二层循环:遍历每个分组对象的属性,把属性名作为<optgroup>的label,属性值作为该分组下的选项列表
  • 第三层循环:遍历每个选项列表,为每个选项生成对应的<option>标签

这样生成的HTML结构就完全符合你想要的格式啦~

内容的提问来源于stack exchange,提问作者Sisi Sajah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:44:15