js table表格排序程式碼例項

admin發表於2017-04-12

如果表格資料比較多一些的話,可能需要按照一定的順序規則檢視資料。

那麼就用到了排序功能,下面就分享一段程式碼例項,它實現了按照數字列的數字大小排序效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
table td a:hover {
  background-color: #0080c0;
}
.one {
  background-color: #80ff00;
}
.two {
  background-color: #ff8040;
}
.three {
  background-color: #008040;
}
table {
  width: 500px;
  height: 500px;
  border: #400040 solid 2px;
  border-collapse: collapse;
}
table td, th {
  border: solid 2px;
}
table th {
  background-color: #c0c0c0;
}
</style>
<script type="text/javascript">
var flag = true;
function loading() {
  var name;
  var tabNode = document.getElementById("tabid");
  var rows = tabNode.rows;
  var rowslength = rows.length;
  for (var x = 1; x < rowslength; x++) {
    if (x % 2 == 0) {
      rows[x].className = "one";
    }
    else {
      rows[x].className = "two";
    }
    rows[x].onmouseover = function () {
      name = this.className;
      this.className = "three";
    }
    rows[x].onmouseout = function () {
      this.className = name;
    }
  }
}
 
function sortAge() {
  var tabNode = document.getElementById("tabid");
  var rows0 = tabNode.rows;
  var rows1 = [];
  for (var x = 1; x < rows0.length; x++) {
    rows1[x - 1] = rows0[x];
  }
  for (var x = 0; x < rows1.length - 1; x++) {
    for (var y = x + 1; y < rows1.length; y++) {
      if (parseInt(rows1[x].cells[1].innerHTML) > parseInt(rows1[y].cells[1].innerHTML)) {
        var temp = rows1[x];
        rows1[x] = rows1[y];
        rows1[y] = temp;
      }
    }
  }
  var ageimg = document.getElementById("ageid");
  if (flag) {
    for (var x = 0; x < rows1.length; x++) {
      rows1[x].parentNode.appendChild(rows1[x]);
    }
    ageimg.innerHTML = "年齡▲";
  }
  else {
    for (var x = rows1.length - 1; x >= 0; x--) {
      rows1[x].parentNode.appendChild(rows1[x]);
    }
    ageimg.innerHTML = "年齡▼"
  }
  flag = !flag;
  loading();
}
window.onload = function () {
  loading();
  var ageid = document.getElementById("ageid");
  ageid.onclick = function () { sortAge() }
}
</script>
</head>
<body>
<table id="tabid">
  <tr>
    <th>課程</th>
    <th><a href="javascript:void(0)" id="ageid">分數</a></th>
    <th>所屬網站</th>
  </tr>
  <tr>
    <td>css教程</td>
    <td>80</td>
    <td>螞蟻部落</td>
  </tr>
  <tr>
    <td>div教程</td>
    <td>85</td>
    <td>螞蟻部落</td>
  </tr>
  <tr>
    <td>js教程</td>
    <td>90</td>
    <td>螞蟻部落</td>
  </tr>
  <tr>
    <td>正規表示式</td>
    <td>86</td>
    <td>螞蟻部落</td>
  </tr>
  <tr>
    <td>jquery教程</td>
    <td>70</td>
    <td>螞蟻部落</td>
  </tr>
  <tr>
    <td>css3教程</td>
    <td>95</td>
    <td>螞蟻部落</td>
  </tr>
</table>
</body>
</html>

相關文章