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

如何在Jenkins Active Choices插件Groovy脚本中遍历嵌套Map/List

解决Jenkins Active Choices参数嵌套复选框问题

问题核心

你的代码存在三个关键问题:

  • 第一种方案中,test_subgroup是列表结构,但未遍历该列表,导致所有子项被合并成一个复选框。
  • 第二种方案中,同一映射内重复使用test_subgroup键,Groovy会自动保留最后一个赋值,因此每个主组仅显示最后一个子项。
  • 所有复选框使用相同的id="option",违反HTML规范,导致标签与复选框的关联失效。

修正后的可运行代码

以下是能正确生成嵌套分组复选框的Groovy脚本:

test_group_map = [
  "id_1": [
    [test_group: "group_1", test_subgroup: ["subgroup_1", "subgroup_2", "subgroup_3"]],
    [test_group: "group_2", test_subgroup: ["subgroup_4", "subgroup_5"]],
  ],
]

html_to_be_rendered = "<ul style='list-style: none;'>"

test_groups = test_group_map[ID]
test_groups.eachWithIndex { group, groupIndex ->
  // 生成主组复选框,使用唯一ID确保标签关联有效
  html_to_be_rendered += """
    <li>
      <input name="value" alt="${group.test_group}" json="${group.test_group}" type="checkbox" class="mainOption" id="group_${groupIndex}">
      <label title="${group.test_group}" for="group_${groupIndex}">${group.test_group}</label>
      <ul style="list-style: none; margin-left: 20px;">
  """
  
  // 遍历子项列表,为每个子项生成独立复选框
  group.test_subgroup.eachWithIndex { subgroup, subIndex ->
    html_to_be_rendered += """
      <li>
        <input name="value" alt="${subgroup}" json="${subgroup}" type="checkbox" class="subOption" id="sub_${groupIndex}_${subIndex}">
        <label title="${subgroup}" for="sub_${groupIndex}_${subIndex}">${subgroup}</label>
      </li>
    """
  }
  
  html_to_be_rendered += "</ul></li>"
}

html_to_be_rendered += "</ul>"
return html_to_be_rendered

关键修正说明

  1. 遍历子项列表:通过eachWithIndex分别遍历主组和子项列表,确保每个子项生成独立的复选框元素。
  2. 唯一ID属性:为每个复选框生成唯一ID(如group_0、sub_0_0),解决HTML标签关联失效问题。
  3. 规范HTML结构:外层包裹完整的<ul>标签,子项添加缩进样式增强层级视觉效果。
  4. 优化字符串拼接:使用+=累加HTML内容,避免重复赋值导致的格式混乱。

可选增强功能

若需要实现"主组选中时自动选中所有子项"的联动效果,可在HTML末尾添加以下JavaScript代码:

<script>
  document.querySelectorAll('.mainOption').forEach(mainCheckbox => {
    mainCheckbox.addEventListener('change', function() {
      this.parentElement.querySelectorAll('.subOption').forEach(subCheckbox => {
        subCheckbox.checked = this.checked;
      });
    });
  });
</script>

内容的提问来源于stack exchange,提问作者Arek Piotrowski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:13:16