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

原生JavaScript实现下拉选项选中后跳转对应HTML页面的问题

你的跳转逻辑位置写错了,应该绑定在选项点击事件里,而非搜索框的键盘输入逻辑中。修改方案如下:

修改步骤

  1. 找到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`;
    }
  });
});
  1. 注意事项
  • 请确保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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:48:02