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

如何使用JavaScript实现Dropdown Menu联动并动态插入选项

Bootstrap 下拉菜单联动实现方案

首先你现有代码存在ID重复问题:两个下拉按钮的id均为dropdownMenuButton1,需先将第二个下拉按钮的id修改为dropdownMenuButton2,同时将其对应的ul标签的aria-labelledby属性也改为dropdownMenuButton2,避免DOM选择冲突。

实现逻辑

通过JS定义分类与子选项的映射关系,监听第一个下拉菜单的选项点击事件,动态替换第二个下拉菜单的选项内容即可。

完整代码示例

1. 分类映射配置

// 可根据业务需求自行扩展各分类对应的子选项
const categoryOptionMap = {
  "Sales": ["Forward Sales", "Sight Sales", "Latest Sales", "Last Month Sales"],
  "Purchases": ["Raw Material Purchase", "Finished Goods Purchase", "Monthly Purchase", "Supplier Purchase"],
  "Registrations": ["New User Registration", "Enterprise Registration", "Personal Registration", "Event Registration"],
  "Notes": ["Receivable Notes", "Payable Notes", "Overdue Notes", "Current Month Notes"],
  "Bills": ["Electricity Bill", "Water Bill", "Rent Bill", "Salary Bill"]
}

2. 原生JS实现(适配Bootstrap 5)

// 获取DOM节点
const firstMenuItems = document.querySelectorAll('#dropdownMenuButton1 + .dropdown-menu .dropdown-item')
const secondMenu = document.querySelector('#dropdownMenuButton2 + .dropdown-menu')
const secondMenuBtn = document.querySelector('#dropdownMenuButton2')

// 绑定第一个下拉选项的点击事件
firstMenuItems.forEach(item => {
  item.addEventListener('click', function(e) {
    e.preventDefault()
    // 获取选中的一级分类
    const selectedCategory = this.textContent.trim()
    // 重置二级下拉按钮默认文案
    secondMenuBtn.textContent = 'Specify Category'
    // 清空二级下拉原有选项
    secondMenu.innerHTML = ''
    // 渲染对应子选项
    categoryOptionMap[selectedCategory].forEach(optionText => {
      const li = document.createElement('li')
      li.innerHTML = `<a class="dropdown-item" href="#">${optionText}</a>`
      secondMenu.appendChild(li)
    })
  })
})

3. jQuery简化实现

const categoryOptionMap = {
  // 映射配置和上面一致
}

$('#dropdownMenuButton1 + .dropdown-menu .dropdown-item').click(function(e) {
  e.preventDefault()
  const selectedCategory = $(this).text().trim()
  $('#dropdownMenuButton2').text('Specify Category')
  const $secondMenu = $('#dropdownMenuButton2 + .dropdown-menu')
  $secondMenu.empty()
  categoryOptionMap[selectedCategory].forEach(optionText => {
    $secondMenu.append(`<li><a class="dropdown-item" href="#">${optionText}</a></li>`)
  })
})

内容的提问来源于stack exchange,提问作者Gabriel Augusto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:54:02