DIV CSS 佈局教程網

用 select 下拉選單做頁籤跳轉:事件委派寫法
編輯:關於JavaScript     

有些頁面的分類入口用下拉選單比一排連結省空間,選完就自動跳轉。這裡用 jQuery 的事件委派實作,程式碼很短。

<!DOCTYPE html>
<html>
<head>
<title>select 跳轉</title>
</head>
<body>
<div class="selectBox">
  <select class="toSlt">
    <option href="https://jichuang.gongchang.cn/pro-161264/">全部分類的商品</option>
    <option href="https://jichuang.gongchang.cn/">普通車床</option>
    <option href="https://jichuang.gongchang.cn/brand/">回轉車床</option>
    <option href="https://jichuang.gongchang.cn/">普通車床</option>
    <option href="https://jichuang.gongchang.cn/brand/">回轉車床</option>
  </select>
</div>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"</script>
<script type="text/javascript">
$(function(){
  var $body = $('body');
  $body.on('change', 'select:has(option[href])', function(e) {
    var _this = $(this);
    var _href = _this.find('option:selected').attr('href');
    location.href = _href;      // 跳轉
  });
});
</script>
</body>
</html>

幾個細節值得說明:

這裡用的是「事件委派」寫法 $body.on('change', selector, handler),把監聽掛在 body 上、用選擇器過濾目標。好處是即使 select 是後來才動態插入的,也能正常運作;若用 $('select').change() 直接綁定,後插入的元素就會失效。

選擇器 select:has(option[href]) 只針對「option 有 href」的下拉選單生效,避免影響頁面上其他 select。

更推薦的標準做法

把目標網址放在 option 的 value 上,語意比自訂 href 屬性更正確(href 不是 option 的合法屬性,HTML 驗證會報錯):

<select id="nav">
  <option value="">請選擇分類</option>
  <option value="/pro-161264/">全部分類的商品</option>
  <option value="/brand/">回轉車床</option>
</select>

<script>
document.getElementById('nav').addEventListener('change', function () {
  if (this.value) location.href = this.value;
});
</script>

另外建議保留一個「請選擇」的空值選項作為預設,否則頁面一載入、使用者用鍵盤上下鍵瀏覽選項時就會立刻觸發跳轉,對鍵盤與螢幕閱讀器使用者都很不友善。若改用 button 搭配選單,讓使用者明確按下才跳,體驗會更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved