如何用JavaScript将子下拉菜单选中项移至主下拉列表顶部?
可以实现,以下是具体方案
我们可以通过JavaScript监听子下拉菜单的点击事件,将选中的课程项添加到主下拉菜单的顶部,同时避免重复添加。
实现步骤:
- 给所有子下拉菜单里的课程链接绑定点击事件,跳过标题类选项(比如文本为"Courses"的项)
- 点击时获取选中的课程文本,生成对应的列表元素
- 检查主下拉菜单顶部是否已存在该课程,防止重复插入
- 将新元素插入到主下拉菜单的最前端
- 可选:更新下拉按钮的显示文本,让选中状态更直观
完整代码示例:
<div class="dropdown"> <p> <h5>Departments</h5> </p> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" style="margin-left:0px;padding-left:0px;">Select <span class="caret"></span></button> <ul class="dropdown-menu main-dropdown"> <li><a tabindex="-1" href="#">MCA</a></li> <li class="dropdown-submenu"> <a class="test" tabindex="-1" href="#">B.Tech <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a tabindex="-1" href="#">Courses</a></li> <li><a tabindex="-1" href="#">EEE</a></li> <li><a tabindex="-1" href="#">Civil</a></li> <li><a tabindex="-1" href="#">Mechanical</a></li> <li><a tabindex="-1" href="#">Computer science</a></li> <li><a tabindex="-1" href="#">Aeronautics</a></li> </ul> </li> <li class="dropdown-submenu"> <a class="test" tabindex="-1" href="#">M.Tech <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a tabindex="-1" href="#">Courses</a></li> <li><a tabindex="-1" href="#">IC Technology</a></li> <li><a tabindex="-1" href="#">Civil</a></li> <li><a tabindex="-1" href="#">DataScience</a></li> <li><a tabindex="-1" href="#">Computer science</a></li> <li><a tabindex="-1" href="#">Environmental Engineering</a></li> </ul> </li> </ul> </div> <script> // 定位主下拉菜单 const mainDropdown = document.querySelector('.main-dropdown'); // 获取所有子下拉菜单的链接 const subMenuLinks = document.querySelectorAll('.dropdown-submenu .dropdown-menu a'); // 给每个子菜单链接绑定点击事件 subMenuLinks.forEach(link => { link.addEventListener('click', function(e) { e.preventDefault(); // 阻止默认跳转行为 const courseText = this.textContent.trim(); // 跳过"Courses"这类标题项 if (courseText === 'Courses') return; // 检查主菜单顶部是否已有该课程,避免重复添加 const topItem = mainDropdown.querySelector('li:first-child a'); if (topItem && topItem.textContent.trim() === courseText) return; // 创建新的课程列表项 const newLi = document.createElement('li'); const newA = document.createElement('a'); newA.setAttribute('tabindex', '-1'); newA.setAttribute('href', '#'); newA.textContent = courseText; newLi.appendChild(newA); // 插入到主下拉菜单的最前面 mainDropdown.insertBefore(newLi, mainDropdown.firstChild); // 可选:更新下拉按钮的显示文本 const dropdownBtn = document.querySelector('.dropdown-toggle'); dropdownBtn.innerHTML = `${courseText} <span class="caret"></span>`; }); }); </script>
代码说明:
- 给主下拉菜单添加
main-dropdown类,方便快速定位元素 - 阻止链接的默认跳转行为,避免页面刷新
- 跳过不需要处理的标题项,只处理实际课程
- 检查重复项,防止同一课程多次出现在顶部
- 动态生成新列表项并插入到主菜单最前端
- 可选的按钮文本更新,提升用户体验
这样就能实现你想要的功能:点击子菜单中的任意课程后,该课程会显示在主下拉列表的顶部位置。
内容的提问来源于stack exchange,提问作者Aaradhya
相关产品推荐
相关产品推荐

