js table表格排序代码实例

快乐打工仔 分类:实例代码

如果表格数据比较多一些的话,可能需要按照一定的顺序规则查看数据。

那么就用到了排序功能,下面就分享一段代码实例,它实现了按照数字列的数字大小排序效果。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>
网站出售中,有意者加微信:javadudu

回复

我来回复
  • 暂无回复内容