DIV CSS 佈局教程網

用 jQuery 調整表格欄位順序的完整實作
編輯:關於JavaScript     

有些後台需要讓使用者自訂表格欄位的顯示順序。這個範例的做法是:把每一欄存進陣列,透過「上移/下移」按鈕交換陣列元素,再重新組裝整個表格。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>調整表格順序</title>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<style type="text/css">
#main{ width:800px; height:400px; margin:auto; text-align:center;
       border:1px solid red; background:#eee; padding-top:100px; }
#tabf{ height:170px; position:relative; }
#showDetail{ left:244px; width:20px; height:15px; line-height:15px;
  border-left:1px solid blue; border-top:1px solid blue;
  border-right:1px solid blue; cursor:pointer; display:none; position:absolute; }
#tab{ margin-top:16px; border-collapse:collapse; position:absolute; }
#tab td{ height:50px; width:50px; line-height:50px; border:1px solid blue; }
#sortTab{ width:170px; height:155px; border:3px outset; background:#ccc;
  position:absolute; top:15px; left:270px; display:none; }
#tdList{ width:90px; height:150px; border:1px inset; position:absolute; }
#opt{ width:80px; height:150px; position:absolute; left:90px; }
.btn{ margin:10px; width:60px; height:20px; }
</style>
<script type="text/javascript">
$(function(){
  index = 0;
  cols = new Array();

  show_Hide_tipBtn(); // 顯示或隱藏表格設定面板
  showResult();       // 文件載入完成時,先把表格各欄同步到面板

  $(".up").click(function(){
    sortColumn(cols, index, "tab", "up");
    showResult();
    $(".sortTd").each(function(m){
      $(this).css("background-color", m == index ? "red" : "");
    });
  });

  $(".down").click(function(){
    sortColumn(cols, index, "tab", "down");
    showResult();
    $(".sortTd").each(function(m){
      $(this).css("background-color", m == index ? "red" : "");
    });
  });
});

function getResult(cols){
  var result = "";
  cols.each(function(n){
    result += "<span style='margin-top:10px;border:1px solid;display:block'
                id='" + n + "' class='sortTd'>" + $(this).text() + "</span>";
  });
  return result;
}

function showResult(){
  // 把表格中各欄的第一列內容顯示到面板上
  cols.length = 0;
  $("#tab tr:first td").each(function(i){
    var col = $("#tab tr td:nth-child(" + (i + 1) + ")");
    cols.push(col); // 將每一欄分別存入陣列

    $("#tdList").html(getResult($(cols)));

    $(".sortTd").click(function(){
      $(".sortTd").css("background-color", "");
      $(this).css("background-color", "red");
      index = parseInt($(this).attr("id"));
    });
  });
}

function show_Hide_tipBtn(){
  $("#tab").mouseover(function(){
    $("#showDetail").css("display", "block");
  }).mouseout(function(){
    $("#showDetail").css("display", "none");
  });

  $("#showDetail").mouseover(function(){
    $(this).css("display", "block");
  }).mouseout(function(){
    $(this).css("display", "none");
  });

  $("#showDetail").click(function(){
    $("#sortTab").slideToggle("slow");
  });
}

function sortColumn(col, t, faId, dir){
  // 已在第一欄卻要上移,或已在最後一欄卻要下移,直接結束
  if (((t == 0) && (dir == "up")) || ((t == col.length - 1) && (dir == "down"))) {
    return false;
  }

  var k = t, idx = 0;
  if (dir == "up")       { idx = k - 1; }
  else if (dir == "down") { idx = k + 1; }

  // 交換陣列中的兩欄
  var temp = col[idx];
  col[idx] = col[k];
  col[k] = temp;

  // 清空原表格後依新順序重建
  $("#" + faId + " tr").each(function(){ $(this).remove(); });

  var trs = col[0].length;
  for (var j = 0; j < trs; j++) {
    var tr = $("<tr></tr>");
    $(col).each(function(){
      tr.append($($(this)[j]));
    });
    $("#" + faId).append(tr);
  }
  index = idx;
}
</script>
</head>
<body>
<div id="main">
  <div id="tabf">
    <div id="showDetail">></div>
    <table id="tab">
      <tr><td>a</td><td>b</td><td>c</td><td>d</td><td>e</td></tr>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
    </table>

    <div id="sortTab">
      <div id="tdList"></div>
      <div id="opt">
        <input type="button" value="UP" class="btn up"/><br/>
        <input type="button" value="DOWN" class="btn down"/><br/>
      </div>
    </div>
  </div>
</div>
</body>
</html>

幾個實作重點:

  • 資料結構是關鍵:先把每一欄的 td 集合存成陣列 cols,之後所有排序操作都只在陣列上進行,最後一次性重建 DOM。
  • sortColumn 開頭的邊界判斷很重要,否則在第一欄按上移會取到 col[-1] 而拋錯。
  • 重建表格時是「先清空 tr,再按新順序 append」,而不是逐格搬移,這樣邏輯最單純。
  • 原範例中的 td::nth-child() 寫法有誤,已修正為 td:nth-child();偽元素寫法在這裡並不適用。
  • 面板項目用 id 存索引,點擊後以 parseInt 取回,這是簡單但有效的「選取目前欄位」做法。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved