写的一个小Demo,小白一枚-.-希望大佬们多多提点意见...
<!DOCTYPE html>
<!--
Demo15.html
<表格的升序降序>
Created by xinquan on 2018-09-07.
Copyright 2018 xinquan. All rights reserved.
-->
<html>
<head>
<meta charset="UTF-8">
<title>Table</title>
<style>
*{
padding: 0;
margin: 0;
}
.fn{
width: 800px;
margin: 0 auto;
/*border: 1px solid #000;*/
border-collapse: collapse;
}
.fn tr{
height: 50px;
}
#head{
background-color: #ccc;
}
.fn tr td{
text-align: center;
border: 1px solid #000;
}
</style>
</head>
<body>
<table class="fn">
<tr id="head">
<td>姓名</td>
<td data-name = "li">力量</td>
<td data-name = "min">敏捷</td>
<td data-name = "zi">智力</td>
</tr>
<tbody id="bod">
<tr>
<td>亚索</td>
<td>17</td>
<td>24</td>
<td>13</td>
</tr>
<tr>
<td>拉克丝</td>
<td>15</td>
<td>22</td>
<td>16</td>
</tr>
<tr>
<td>石头人</td>
<td>19</td>
<td>15</td>
<td>20</td>
</tr>
<tr>
<td>妖姬</td>
<td>23</td>
<td>15</td>
<td>14</td>
</tr>
</tbody>
</table>
</body>
</html>
<script>
//伪json数据,因为我觉得一直通过dom操作获取元素的值有点麻烦,所以想通过数组对象存储
var people=[
{
"name":"亚索",
"li":17,
"min":24,
"zi":13
},
{
"name":"拉克丝",
"li":15,
"min":22,
"zi":16
},
{
"name":"石头人",
"li":19,
"min":15,
"zi":20
},
{
"name":"妖姬",
"li":23,
"min":15,
"zi":14
}
]
//获取表头
var oHead=document.getElementById("head");
//获取tbody
var oBod=document.getElementById("bod");
//给表头事件代理通过每次点击的事件源的data来判定说选的属性
oHead.onclick=function(e){
var e=e||event;
var target=e.target||e.srcElement;
if(target.getAttribute("data-name")=="li"){
//.s升序降序的开关门,第一次点击时是false,每次点击改变它的值
if(target.s){
//封装的冒泡排序的方法,通过传递参数true/false来改变排序的方式
var arrs=paixu(people,"li",true);
target.s=false;
}else{
target.s=true;
var arrs=paixu(people,"li",false);
}
//通过str给tbody添加内容,这里一直操作dom元素,有点消耗性能,暂时想不到好的方法
var str="";
for(var i=0;i<arrs.length;i++){
str+="<tr><td>"+arrs[i]["name"]+"</td><td>"+arrs[i]["li"]+"</td><td>"+arrs[i]["min"]+"</td><td>"+arrs[i]["zi"]+"</td></tr>";
}
oBod.innerHTML=str;
}
if(target.getAttribute("data-name")=="min"){
if(target.s){
var arrs=paixu(people,"min",true);
target.s=false;
}else{
target.s=true;
var arrs=paixu(people,"min",false);
}
var str="";
for(var i=0;i<arrs.length;i++){
str+="<tr><td>"+arrs[i]["name"]+"</td><td>"+arrs[i]["li"]+"</td><td>"+arrs[i]["min"]+"</td><td>"+arrs[i]["zi"]+"</td></tr>";
}
oBod.innerHTML=str;
}
if(target.getAttribute("data-name")=="zi"){
if(target.s){
var arrs=paixu(people,"zi",true);
target.s=false;
}else{
target.s=true;
var arrs=paixu(people,"zi",false);
}
var str="";
for(var i=0;i<arrs.length;i++){
str+="<tr><td>"+arrs[i]["name"]+"</td><td>"+arrs[i]["li"]+"</td><td>"+arrs[i]["min"]+"</td><td>"+arrs[i]["zi"]+"</td></tr>";
}
oBod.innerHTML=str;
}
}
//冒泡排序改编
function paixu(arr,info,el){
var temp;
for(var i=1;i<arr.length;i++){
if(el){
for(var j=0;j<arr.length-i;j++){
//比较的是数组对象需要比较的某个值改变的是这个对象的位置
if(arr[j][info]>arr[j+1][info]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}else{
for(var j=0;j<arr.length-i;j++){
if(arr[j][info]<arr[j+1][info]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
return arr;
}
</script>