如何使用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
相关产品推荐
相关产品推荐

