原生JavaScript实现下拉选项选中后跳转对应HTML页面的问题
你的跳转逻辑位置写错了,应该绑定在选项点击事件里,而非搜索框的键盘输入逻辑中。修改方案如下:
修改步骤
- 找到JS代码中遍历
optionsList绑定点击事件的部分,新增跳转逻辑:
optionsList.forEach(o => { o.addEventListener("click", () => { const labelEl = o.querySelector("label"); selected.innerHTML = labelEl.innerHTML; optionsContainer.classList.remove("active"); // 新增跳转逻辑 const pageName = labelEl.innerText.trim().toLowerCase(); // 过滤不需要跳转的Dummy选项,不需要可以删掉这个判断 if (pageName !== 'dummy') { window.location.href = `${pageName}.html`; } }); });
- 注意事项
- 请确保
dhanmondi.html、bashundhara.html等目标页面和当前页面处于同一级目录下,否则需要补全对应页面的相对/绝对路径 - 如果你的页面命名和标签文字大小写不一致,自行调整
pageName的大小写处理逻辑即可
完整修改后JS代码
const selected = document.querySelector(".selected"); const optionsContainer = document.querySelector(".options-container"); const searchBox = document.querySelector(".search-box input"); const optionsList = document.querySelectorAll(".option"); selected.addEventListener("click", () => { optionsContainer.classList.toggle("active"); searchBox.value = ""; filterList(""); if (optionsContainer.classList.contains("active")) { searchBox.focus(); } }); optionsList.forEach(o => { o.addEventListener("click", () => { const labelEl = o.querySelector("label"); selected.innerHTML = labelEl.innerHTML; optionsContainer.classList.remove("active"); const pageName = labelEl.innerText.trim().toLowerCase(); if (pageName !== 'dummy') { window.location.href = `${pageName}.html`; } }); }); searchBox.addEventListener("keyup", function(e) { filterList(e.target.value); }); const filterList = searchTerm => { searchTerm = searchTerm.toLowerCase(); optionsList.forEach(option => { let label = option.firstElementChild.nextElementSibling.innerText.toLowerCase(); if (label.indexOf(searchTerm) != -1) { option.style.display = "block"; } else { option.style.display = "none"; } }); };
内容的提问来源于stack exchange,提问作者Ashir
相关产品推荐
相关产品推荐

