DIV CSS 佈局教程網

用 jQuery 與 select 下拉選單即時過濾表格資料
編輯:JQuery特效代碼     

表格欄位多、資料量大時,讓使用者自己用下拉選單挑選條件來篩選,比拉一整排搜尋框友善。這個做法的巧妙之處在於:下拉選單的選項不是手寫的,而是直接從表格內容動態萃取,資料一改選單就跟著改。

表格結構

<table id="example">
  <thead>
    <tr><th>Name</th><th>Surname</th></tr>
  </thead>
  <tbody>
    <tr><td>Michael</td><td>Jordan</td></tr>
    <tr><td>Michael</td><td>Jackson</td></tr>
    <tr><td>Bruno</td><td>Mars</td></tr>
  </tbody>
</table>

過濾邏輯

// 依表頭欄位數動態產生對應的 select
$("#example > thead th").each(function(i) {
  $("<select />")
    .attr("data-index", i)
    .html($("<option />"))
    .change(function() {
      $("#example > tbody > tr").show().filter(function() {
        var comb = [], children = $(this).children();
        children.each(function(i) {
          var value = $("select[data-index='" + i + "']").val();
          if (value == $(this).text() || value == "") comb.push(1);
        });
        return comb.length != children.length;
      }).hide();
    })
    .appendTo("body");
});

// 把每欄實際出現過的值補進對應的 select 當選項
$("#example > tbody tr").each(function() {
  $(this).children().each(function(i) {
    var that = $(this);
    var select = $("select[data-index='" + i + "']");
    if (!select.children().filter(function() {
      return $(this).text() == that.text();
    }).length) {
      select.append($("<option />").text($(this).text()));
    }
  });
});

運作方式拆解

第一段迴圈依表頭欄位數量產生同樣數量的 select,並用 data-index 記住自己負責第幾欄——這個自訂屬性是後續多選單聯動的關鍵,讓每個下拉選單都能反查自己該比對哪一欄。

第二段迴圈走訪所有資料列,把每個儲存格的值丟進對應的 select。寫入前先用 filter 檢查有沒有重複,所以 Michael 只會出現一次。

過濾本身用了個小技巧:對每一列建立一個 comb 陣列,逐欄比對「選單的值等於儲存格文字」或「選單是空的(代表不限制)」,符合就 push 一個 1。最後只要 comb 的長度不等於欄位數,就代表有欄位沒通過條件,該列隱藏。多個下拉選單因此是「 AND 」的關係,可以疊加篩選。

這個模式很適合套用在後台列表上;若資料量是幾千筆以上,建議改由伺服器端做過濾與分頁,把整批 DOM 塞進瀏覽器再逐一比對會明顯卡頓。

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