萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Select 下拉選單直接跳轉頁面:onchange 事件與 location.href 實現

核心實現

<select id="page-jump" onchange="jumpPage(this)">
  <option value="" disabled selected>-- 請選擇頁面 --</option>
  <option value="/home">首頁</option>
  <option value="/products">產品中心</option>
  <option value="/about">關於我們</option>
  <option value="/contact">聯繫我們</option>
  <option value="https://example.com">外部鏈接</option>
</select>

<script>
function jumpPage(select) {
  const url = select.value;
  if (!url) return; // 未選擇有效選項

  // 同窗口跳轉
  window.location.href = url;

  // 或新標籤頁打開:window.open(url, '_blank');

  // 重置下拉框(可選)
  // select.selectedIndex = 0;
}
</script>

進階封裝:可復用跳轉組件

class PageJumper {
  constructor(selectEl, options = {}) {
    this.select = typeof selectEl === 'string' ? document.querySelector(selectEl) : selectEl;
    this.newTab = options.newTab || false;
    this.reset = options.reset !== false; // 默認重置
    this.bind();
  }

  bind() {
    this.select.addEventListener('change', () => this.jump());
  }

  jump() {
    const url = this.select.value;
    if (!url) return;
    if (this.newTab) window.open(url, '_blank', 'noopener,noreferrer');
    else window.location.href = url;
    if (this.reset) this.select.selectedIndex = 0;
  }

  // 動態更新選項
  setOptions(options) {
    this.select.innerHTML = options.map(o => 
      ``
    ).join('');
  }
}

// 使用
new PageJumper('#page-jump', { newTab: false, reset: true });

無障礙增強

  • 添加 `aria-label="頁面快速跳轉"` 於 `