首页 > 试题广场 >

如下图,请实现表格信息的排序功能,当点击表头的属性区域,将表

[问答题]
如下图,请实现表格信息的排序功能,当点击表头的属性区域,将表格信息进行排序切换功能,即第一次点击为降序排序,再一次点击进行升序排序。
推荐

排序算法

Js的Dom和事件相关操作。

编辑于 2014-12-05 10:28:40 回复(3)
我看很多人的回答都没考虑清楚:
1、点击表头,也可以是点击“姓名”,需要区分中文和数字的排序方式;
2、“第一次点击为降序排序,再一次点击进行升序排序”,需要可逆,并且如果点击“力量”一次,再点击“敏捷”,然后再次点击“力量”,需要实现的是力量的降序,而不是力量的升序;
3、可扩展性,如果属性不止这4个,那么很多人的代码直接作废。

贴代码,原生JS写的:
var the_table=document.getElementById("the_table");
var the_table_tr=the_table.getElementsByTagName("tr");
var the_table_tbody=the_table.getElementsByTagName("tbody")[0];
var the_table_head_td=the_table_tr[0].getElementsByTagName("td");
var click_switch=[];
for(i=0;i<the_table_head_td.length;i++){
    (function each_one(_i){
        click_switch.push(0);
        the_table_head_td[_i].onclick=function(){
            for(q=0;q<click_switch.length;q++){
                if(q!==_i){
                    click_switch[q]=0;
                }
            }
            var temp_arr=[];
            var the_table_tr_arr=[];
            for(j=1;j<the_table_tr.length;j++){
                temp_arr.push(the_table_tr[j].getElementsByTagName("td")[_i].innerHTML);
                the_table_tr_arr.push(the_table_tr[j].cloneNode(true));
            };
            var tr_length_temp=the_table_tr.length
            for(x=1;x<tr_length_temp;x++){
                the_table_tbody.removeChild(the_table_tbody.getElementsByTagName("tr")[1]);
            }
            if(temp_arr[0]*1){
                temp_arr.sort(function compare(a,b){return a-b;});
            }else{
                temp_arr.sort(function(a,b){return a<b?-1:1;});
            }
            if(click_switch[_i]==1){
                click_switch[_i]=0;
                for(k=temp_arr.length-1;k>=0;k--){
                    (function each_two(_k){
                        for(vv=0;vv<the_table_tr_arr.length;vv++){
                            if(temp_arr[_k]==the_table_tr_arr[vv].getElementsByTagName("td")[_i].innerHTML){
                            
                                the_table_tbody.appendChild(the_table_tr_arr[vv]);
                            }
                        }
                    })(k);
                }
            }else{
                click_switch[_i]=1;
                for(k=0;k<temp_arr.length;k++){
                    (function each_two(_k){
                        for(vv=0;vv<the_table_tr_arr.length;vv++){
                            if(temp_arr[_k]==the_table_tr_arr[vv].getElementsByTagName("td")[_i].innerHTML){
                            
                                the_table_tbody.appendChild(the_table_tr_arr[vv]);
                            }
                        }
                    })(k);
                }
            }
        }
    })(i)
}
发表于 2015-03-24 11:54:27 回复(3)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
	<title>表格排序</title>
</head>
<style type="text/css">
	table{
		width: 500px;
		height: 200px;
		position: relative;
		border-width: 0px 0px 1px 1px;
    	border-style: solid;
	}	
	tr{
		height: 40px;
	}
	td,th{
		width: 25%;
		 border-width: 1px 1px 0 0;
    	 border-style: solid;
		padding: 0;
		margin: 0;
	}
</style>
<body>
<table id="table" cellpadding="1" cellspacing="1">
	<thead>
		<tr bgcolor="grey">
			<th>姓名</th>
			<th onclick="sortTable(1)">力量</th>
			<th onclick="sortTable(2)">敏捷</th>
			<th onclick="sortTable(3)">智力</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<th>德鲁伊</th>
			<td>17</td>
			<td>24</td>
			<td>13</td>
		</tr>
		<tr>
			<th>月之骑士</th>
			<td>15</td>
			<td>22</td>
			<td>16</td>
		</tr>
		<tr>
			<th>众神归王</th>
			<td>19</td>
			<td>35</td>
			<td>20</td>
		</tr>
		<tr>
			<th>流浪剑客</th>
			<td>23</td>
			<td>15</td>
			<td>14</td>
		</tr>
	</tbody>
</table>
<script type="text/javascript">
	var isSort = [false,false,false];//标记是否排过序
	function sortTable (colNo) {
		var rowsArray = [];//表格中所有行的集合
		var colsArray = [];//表格中所有列的集合
		var tbody = document.getElementsByTagName('tbody')[0];
		//初始化行和列
		for (var i = 0; i < tbody.rows.length; i++) {
			rowsArray[i] = tbody.rows[i];
			colsArray[i] = rowsArray[i].cells[colNo];
		}
		
		//排序
		console.log(isSort[colNo])		
		if (!isSort[colNo]) {//isSort为false时,降序排列
			isSort[colNo] = true;
			colsArray.sort(function (a,b) {
				return b.innerHTML - a.innerHTML;//将被点的那一列降序排序
			});
		}else{
			//此时已经降序排序过了,对数组逆序即可
			colsArray.reverse();
			isSort[colNo] = false;
		}
		//当某一列排序后将表格所有元素的值放到新的数组中
		var rowsTempArray = [];
		for (var i = 0; i < rowsArray.length; i++) {
			var colsTempArray = [];
			for (var j = 0; j < colsArray.length; j++) {
				//将i行的所有列的内容保存在colsTempArray[j]中
				colsTempArray[j] = colsArray[i].parentNode.cells[j].innerHTML;
			}
			//将一行内容保存到rowsTempArray。
			rowsTempArray[i] = colsTempArray;
		}
		//重绘页面
		for (var i = 0; i < rowsArray.length; i++) {
			for (var j = 0; j < colsArray.length; j++) {
				rowsArray[i].cells[j].innerHTML = rowsTempArray[i][j];	
			}
		}
	}
</script>
</body>
</html>

编辑于 2015-09-12 16:15:17 回复(9)
//使用 的是jquery jquery-1.5.1.min.js    不是纯js

$(function(){
    var aTdCont = [];
    var thi = 0;
    var setTrIndex = function(tdIndex){
        for(i=0;i < aTdCont.length; i++){
            var trCont = aTdCont[i];
            $("tbody tr").each(function() {
                var thisText = $(this).children("td:eq("+tdIndex+")").text();
                if(thisText == trCont){
                    $("tbody").append($(this));
                }
             });        
        }
    }
    var compare_down = function(a,b){
            return a-b;
    }
    
    var compare_up = function(a,b){
            return b-a;
    }
    var fSort = function(compare){
        aTdCont.sort(compare);
    }
   
    var fSetTdCont = function(thIndex){
            $("tbody tr").each(function() {
                var tdCont = $(this).children("td:eq("+thIndex+")").text();
                aTdCont.push(tdCont);
            });
    }
    var clickFun = function(thindex){
        aTdCont = [];
        var nThCount = thindex;
        fSetTdCont(nThCount);
    }
   
    $("th").toggle(function(){
        thi= $(this).index();
        clickFun(thi);
        fSort(compare_up);
        setTrIndex(thi);
    },function(){
        clickFun(thi);    
        fSort(compare_down);
        setTrIndex(thi);
    })        
})
发表于 2015-01-27 20:36:46 回复(0)
这个问题比较有趣,请点击这里查看源代码:
http://codepen.io/Dophin/pen/gpKZvP

发表于 2015-07-15 23:39:47 回复(1)
个人觉得大家的算法都是一样的,但是我斗胆贴上自己的代码,我使用的原型继承的方式来封装一个函数,感觉的结构会比较清晰,整个js部分也不像上面几位那样有太多的jQuery的选择器,也容易扩展,希望大家提提建议。
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<table border="1" cellpadding="10" id="sortTable">
		<thead align="left">
			<tr>
				<th>姓名</th>
				<th>力量</th>
				<th>敏捷</th>
				<th>智力</th>
			</tr>
		</thead>
		<tbody></tbody>
	</table>
</body>
<script> </script>
</html>
function SortTable( dom ) {
    	this.dom = dom;
    	this.init();
    }

    var propertys = {
    	init : function() {
    		this.setting();
    		this.render();
    		this.bindEvent();
    	},
    	setting : function() {
        //数据没有那么重要吧
    		this.data = [
    			{name : "德鲁伊", power : 17, speed : 24, intel : 13},
    			{name : "napoleon", power : 23, speed : 14, intel : 33},
    			{name : "覃小夫", power : 122, speed : 122, intel : 156},
    			{name : "敏感词", power : 10, speed : 10, intel : 120}
    		];
    		this.isClick = {
    			power : null,
    			speed : null,
    			intel : null
    		};
    	},
    	render : function() {
    		var str = '';
    		for ( var i = 0; i < this.data.length; i++ ) {
    			str += '<tr>';
    			for ( var pro in this.data[i] ) {
    				str += '<td>' + this.data[i][pro] + '</td>';
    			}
    			str += '</tr>';
    		}

    		this.dom.innerHTML = str;
    	},
    	bindEvent : function() {
    		this.clickEvent = this.handleClick.bind( this );
                //让table元素来响应click事件
    		this.dom.parentNode.addEventListener( 'click', this.clickEvent, false );
    	},
    	handleClick : function(event) {
    		var tag = event.target.innerHTML.toLowerCase();
    		switch( tag ) {
    			case '力量':
    				this.sort( 'power' );
    				break;
    			case '敏捷':
    				this.sort( 'speed' );
    				break;
    			case '智力':
    				this.sort( 'intel' );
    				break;
    		}
    		this.render();
    	},
    	sort : function(property) {
    		this.data.sort( function(a,b) {
    			if ( this.isClick[property] ) 
    				return a[property] > b[property];
    			else
    				return a[property] < b[property];
    			
    		}.bind(this) );
    		this.isClick[property] = !this.isClick[property];
    	},
    	destroy : function() {
    		this.data = null;
    		this.isClick = null;
    		this.dom.parentNode.removeEventListener( 'click', this.clickEvent );
    		this.dom = null;
    	}
    };

    SortTable.prototype = Object.create( propertys );

var tableSorting = new SortTable( document.querySelector( '#sortTable tbody'));

发表于 2016-09-02 16:55:50 回复(2)
<!DOCTYPE html>
<html>
<head>
	<title>Test</title>
</head>
<body>

<style type="text/css">
	table,th,td{
		border: 1px solid #ccc;
		border-collapse: collapse;
	}
	th,td{
		width: 70px;
		text-align: center;
	}
	th:hover{
		background-color: #09f;
	}
</style>

<table>
	<tr>
		<th>姓名</th>
		<th>力量</th>
		<th>敏捷</th>
		<th>智力</th>
	</tr>
	<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>
</table>



<script type="text/javascript">
	var thArr = document.querySelectorAll("th");
	var tdArr = document.querySelectorAll("td");
	var tdContentArr = [];
	var ascend = false;  //升序排序标志位
	function convertType(index,str){
		if(index !== 0){
			return parseInt(str);
		}
		else{
			return str.toString();
		}
	}
	for(let i=0;i<(tdArr.length/thArr.length);i++){
		tdContentArr[i] = []; //二维数组
		for(let j=0;j<thArr.lengt敏感词dContentArr[i].push(tdArr[i*thArr.length+j].innerHTML);
		}
	}
	console.log(tdContentArr);

	for(let i=0;i<thArr.length;i++){
		thArr[i].onclick = function(){
			let index = i;  //点击的第几列
			//冒泡排序  升序排序
			for(let j=0;j<(tdArr.length/thArr.length);j++){
				for(let k=1;k<(tdArr.length/thArr.length);k++){
					if(convertType(index,tdContentArr[k][index])<convertType(index,tdContentArr[k-1][index])){
						//升序排序
						let temp;
						for(let x=0;x<thArr.length;x++){
							//交换两行内容
							temp = tdContentArr[k][x];
							tdContentArr[k][x] = tdContentArr[k-1][x];
							tdContentArr[k-1][x] = temp;
						}
					}
				}
			}
			console.log(tdContentArr);
			var rowItems = thArr.length;  //每行的数目
			var colItems = tdArr.length/thArr.length;
			//升序排序
			if(ascend){
				for(let i=0;i<tdArr.length;i++){
					tdArr[i].innerHTML = tdContentArr[parseInt(i/rowItems)][parseInt(i%rowItems)];
				}
			}
			else{
				//降序序排序
				for(let i=0;i<tdArr.length;i++){
					tdArr[i].innerHTML = 
						tdContentArr[colItems-1-parseInt(i/rowItems)][parseInt(i%rowItems)];
				}
			}
			ascend = !ascend;
		}
	}
</script>

</body>
</html>

发表于 2017-08-30 17:07:07 回复(0)
<!DOCTYPE html>
<html>
<head>
	<title>sort table</title>
	<meta charset="utf-8">
<style type="text/css">
*{
	padding:0;
	margin:0;
}
table tr td{
	width:100px;
	height:30px;
	line-height:30px;
	text-align:center;
}
</style>
</head>
<body>
<table border="1" cellspacing="0" >
	<tr style="background:#eee;">
		<td>姓名</td>
		<td>力量</td>
		<td>敏捷</td>
		<td>智力</td>
	</tr>
	<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>
</table>
</body>
<script type="text/javascript">
var thead=document.getElementsByTagName("tr")[0];
var td=thead.getElementsByTagName("td");
for(var i=0;i<td.length;i++){
	td[i].index=i;
	td[i].onclick=function(){
		sortTable(this.index);
	};
}
var trlist=document.getElementsByTagName("tr");
var table=document.getElementsByTagName("table")[0];
function sortTable(index){
	console.log(index);
	var tr=Array.prototype.slice.call(trlist,1); 
	tr.sort(function(a,b){
		var td1=a.getElementsByTagName("td")[index].innerText;
		var td2=b.getElementsByTagName("td")[index].innerText;
		if(td1*1){
			return td1-td2;
		}else{
			return td1>td2?-1:1;
		}
	});
	//console.log(tr);
	table.innerHTML="";
	table.appendChild(thead);
	for(var i=0;i<tr.length;i++){
		table.appendChild(tr[i]);
	}
}
</script>
</html>

发表于 2017-04-25 20:48:17 回复(0)
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>对列表进行排序</title>
</head>
<body>
	<script type="text/javascript">
	var obj1 = {
		name:'德鲁伊',
		strength:'17',
		veh:'24',
		intelligence:'13'
	};
	var obj2 = {
		name:'月之骑士',
		strength:'15',
		veh:'22',
		intelligence:'16'
	};
	var obj3 = {
		name:'众神之王',
		strength:'19',
		veh:'15',
		intelligence:'20'
	};
	var obj4 = {
		name:'流浪剑客',
		strength:'23',
		veh:'15',
		intelligence:'14'
	};
	var arr = [obj1,obj2,obj3,obj4];
	window.onload = function(){
		var tr = document.getElementsByTagName('tr');
		var th = document.getElementsByTagName('th');
		function insert(){
			for (var i = 1; i < tr.length; i++) {
			tr[i].innerHTML = '<td>'+arr[i-1].name+'</td>'+'<td>'+arr[i-1].strength+'</td>'+'<td>'+arr[i-1].veh+'</td>'+'<td>'+arr[i-1].intelligence+'</td>';
			}
		}
		insert();
		function sortByAttr1(attr){
			return function(obj1,obj2){
				var a = obj1[attr];
				var b = obj2[attr];
				return a-b;
			}
		}
		function sortByAttr2(attr){
			return function(obj1,obj2){
				var a = obj1[attr];
				var b = obj2[attr];
				return b-a;
			}
		}
		var flag;
		for (var i = 1; i < th.length; i++) {
			switch(th[i].innerHTML){
					case '力量': th[i].attr='strength';break;
					case '敏捷': th[i].attr = 'veh';break;
					case '智力': th[i].attr = 'intelligence';break;
					default: alert('error');
				}
			th[i].onclick = function(){
				if(flag == false){
					arr.sort(sortByAttr1(this.attr));
					flag = true;
				}else{
					arr.sort(sortByAttr2(this.attr));
					flag = false;
				}
				
				insert();
			};
		}
	}
	</script>
	<table cellspacing="0px" cellpadding="0px" border="1px">
		<tr><th>姓名</th><th>力量</th><th>敏捷</th><th>智力</th></tr>
		<tr></tr>
		<tr></tr>
		<tr></tr>
		<tr></tr>
	</table>
</body>
</html>

发表于 2016-06-23 16:51:42 回复(0)
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style>

td{text-align:center;}

</style>

</head>
<body>
<table id="table" border="1px" width="350px;">
<thead>
<tr><td>姓名</td><td>力量</td><td>敏捷</td><td>智力</td></tr>
</thead>
<tbody>
<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>
<script>
var oDiv=document.getElementById('table');
var t=oDiv.tBodies[0].rows;
var h=oDiv.getElementsByTagName('thead')[0].getElementsByTagName('td');
var arr=[];
function get(x)
{
for(var i=0;i<oDiv.tBodies[0].rows.length;i++)
{
arr[i]=oDiv.tBodies[0].rows[i];
}

arr.sort(function(tr1,tr2)
{
var n1=parseInt(tr1.cells[x].innerHTML);
var n2=parseInt(tr2.cells[x].innerHTML);
return n1-n2;
})

for(var i=0;i<arr.length;i++)
{
oDiv.appendChild(arr[i]);
}
}
for(var i=1;i<h.length;i++)
{
h[i].index=i;
h[i].onclick=function()
{
get(this.index);
}
}
</script>
</body>
</html>

发表于 2015-01-26 13:47:45 回复(0)
利用一个开关和数组sort方法进行排序,大概这样吧:
arr.sort(function(a,b){
    return a-b;
});----升序排序

arr.sort(function(a,b){
    return b-a;
});----降序排序


发表于 2014-12-02 17:57:45 回复(1)
<script>
     var isSort=[false,false,false]
     function sort(colName){
        var rowsArray = [];
        $('tbody tr').each(function(){
           rowsArray.push($(this))
        })
        if(!isSort[colName]){
            isSort[colName]=true
            rowsArray.sort((a,b)=>{
                return a.children().eq(colName).text()-b.children().eq(colName).text()})
        }else{
            isSort[colName]=false
            rowsArray.sort((a,b)=>{
                return b.children().eq(colName).text()-a.children().eq(colName).text()})

        }
        $('tbody').empty()
        rowsArray.forEach((item)=>{
            $('tbody').append(item)
        })
         }  
</script>
发表于 2023-04-09 13:59:23 回复(0)
<table >     <thead id="jsThead">         <tr>             <th>姓名</th>             <th>力量</th>             <th>敏捷</th>             <th>智力</th>         </tr>     </thead>     <tbody id="jsTable">                  <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>

<style>
    body,html{
    padding: 0;
    margin: 0;
    font-size: 14px;
    color: #000000;
}
table{
    border-collapse: collapse;
    width: 100%;
    table-layout: fixed;
}
thead{
    background: #3d444c;
    color: #ffffff;
}
td,th{
    border: 1px solid #e1e1e1;
    padding: 0;
    height: 30px;
    line-height: 30px;
    text-align: center;
}

</style>
<script>
    function sorts(type,order){      var oJsList = document.getElementById("jsTable");
            var aTr = oJsList.getElementsByTagName("tr");
            
            var len = aTr.length;
            var col;
            switch(type) {
                case 0:
                    col = 0;
                    break;
                case 1:
                    col = 1;
                    break;
                case 2:
                    col = 2;
                    break;
                case 3:
                    col = 3;
                    break;
            }
            aTr = Array.prototype.slice.call(aTr);
            console.log(col)
            if(col == 0){
                aTr.sort(function (val1,val2){
                                     var v1 = val1.getElementsByTagName("td")[col].innerText;                     var v2 = val2.getElementsByTagName("td")[col].innerText;                                         if (order == "asc") {                                                  return v2.localeCompare(v1);                     } else {                         return v1.localeCompare(v2);                     }
                })
            }else{
                aTr.sort(function (val1,val2) {
                                         var v1 = parseFloat(val1.getElementsByTagName("td")[col].innerText);                     var v2 = parseFloat(val2.getElementsByTagName("td")[col].innerText);                                         if (order == "asc") {                                                  return v1 - v2;                     } else {                         return v2 - v1;                     }                 });
            }
            
            for (var i = 0; i < len; i++) {
                oJsList.appendChild(aTr[i]);
            }
}
 var oJsTable = document.getElementById("jsThead");
 var thList = oJsTable.getElementsByTagName('tr')[0].children;
for(var s=0;s<thList.length;s++){     thList[s].index=s;     thList[s].num = 1;     thList[s].onclick=function(){         if(this.num%2 != 0){             console.log(this.index)             sorts(this.index,'asc');             this.num = this.num+1;         }else{             sorts(this.index,'desc');             this.num = this.num-1;         }     }
}
</script>

发表于 2018-12-05 11:02:30 回复(0)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        table {
            width: 400px;
            border-collapse: collapse;
            table-layout: fixed;
        }
        thead {
            background-color: lightgreen;
        }
        table td,table th {
            height: 30px;
            line-height: 30px;
            border: 1px solid #000;
            text-align: center;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>姓名</th>
                <th>力量</th>
                <th>敏捷</th>
                <th>智力</th>
            </tr>
        </thead>
                <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>
    </table>
    <script type="text/javascript">
        var table = document.querySelector('table');
        var thead = table.querySelector('thead');
        var tbody = table.querySelector('tbody');
        var ths = thead.querySelectorAll('th');
        var trs = tbody.querySelectorAll('tr');
        for(var i=0;i < ths.length;i++) {
            ths[i].index = i;
        }
        trs = Array.prototype.slice.call(trs);
        var isSort = [];
        isSort[1] = isSort[2] = isSort[3] = true;
        var col;
        thead.addEventListener('click',function(e) {

            var target = e.target || window.event;
            col = target.index;        
            isSort[col] = !isSort[col];
            trs.sort(function(val1,val2) {
                v1 = parseInt(val1.querySelectorAll('td')[col].innerText);
                v2 = parseInt(val2.querySelectorAll('td')[col].innerText);
                if(isSort[col] ) {
                    return v1-v2;
                }
                return v2-v1;
            })
            trs.forEach(function(item) {
            console.log(item);
            tbody.appendChild(item);
        })
        });

    </script>
</body>
</html>
发表于 2018-09-10 10:06:06 回复(0)
(function () {
    //记录升降序
    var isDesc = true;
    function sortTable(column) {
        var tbody = document.getElementsByTagName('tbody')[0];
        var nodes = tbody.childNodes;
        var results = document.createDocumentFragment();
        //去除'text'类型节点
        nodes.forEach(function(e) {
            if (e.nodeType === 1) results.append("e");
        });
        if (column !== 0) {
          //如果点击的是第一列,无效
          Array.prototype.sort.call(results, function(a, b) {
              var result = toNumber(a.childNodes[column]) - toNumber(b.childNodes[column]);
              if (isDesc) result = -result;
              return result;
          });
          //排序结果
          tbody.innerHTML = '';
          tbody.appendChild(results);
          isDesc = false;
        }
    }

    function toNumber(a) {
       return parseInt(a.innerHTML.trim()); 
    }
    return sortTable;
}())

发表于 2017-09-21 21:14:30 回复(0)
<body>
<table border="1" width="40%">
<thead>
<tr>
<th>姓名</th>
<th>力量</th>
<th>敏捷</th>
<th>智力</th>

</tr>
</thead>
<tbody>
<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>
</tbody>
</table>
<script>
//构造记录
function Record(name, power, quick, cute) {
this.name = name;
this.power = power;
this.quick = quick;
this.cute = cute;
}
var isFirst = [true, true, true, true];
var propertys = ['name', 'power', 'quick', 'cute'];
//收集点击的按钮
var ths = [];
var titles = document.querySelectorAll('thead tr th');
for (var i = 0; i < titles.length; i++) {
var cur = titles[i];
ths.push(cur);
}
//收集待排序数据
var records = [];
var trs = document.querySelectorAll('tbody tr');
for (var i = 0; i < trs.length; i++) {
var tds = trs[i].querySelectorAll('td');
var name = tds[0].innerHTML;
var power = parseInt(tds[1].innerHTML);
var quick = parseInt(tds[2].innerHTML);
var cute = parseInt(tds[3].innerHTML);
var record = new Record(name, power, quick, cute);
records.push(record);
}
//事件触发
for (var i = 0; i < titles.length; i++) {
(function(i) {
ths[i].addEventListener('click', function() {
//排序
records.sort(mycompare(propertys[i], isFirst[i]));
//切换升降序
isFirst[i] = !isFirst[i];
//重新渲染数据
render();
}, false);
})(i);
}
//比较函数
function mycompare(property, isFirst) {
return function(obj1, obj2) {
var a = obj1[property];
var b = obj2[property];
if (typeof a == 'number' && typeof b == 'number') {
if (isFirst) {
return b - a;
} else {
return a - b;
}
} else {
if (isFirst) {
return b.localeCompare(a);
} else {
return a.localeCompare(b);
}
}
};
}
//重新渲染数据
function render() {
for (var i = 0; i < trs.length; i++) {
var cur = trs[i];
var tds = cur.querySelectorAll('td');
tds[0].innerHTML = records[i].name;
tds[1].innerHTML = records[i].power;
tds[2].innerHTML = records[i].quick;
tds[3].innerHTML = records[i].cute;
}
}

</script>
</body>
发表于 2017-08-25 13:52:24 回复(0)
<table border="1" style="border-collapse:collapse;" id="test">
  <thead>
    <th>姓名</th>
    <th>力量</th>
    <th>敏捷</th>
    <th>智力</th>
    <th>物理防御</th>
  </thead>
  <tbody>
    <tr>
      <td>德鲁伊</td>
      <td>17</td>
      <td>24</td>
      <td>13</td>
      <td>24</td>
    </tr>
      <tr>
      <td>月之骑士</td>
      <td>15</td>
      <td>24</td>
      <td>22</td>
      <td>16</td>
    </tr>
      <tr>
      <td>众神之王</td>
      <td>19</td>
      <td>15</td>
      <td>24</td>
      <td>20</td>
    </tr>
      <tr>
      <td>流浪剑客</td>
      <td>23</td>
      <td>15</td>
      <td>24</td>
      <td>14</td>
    </tr>
     <tr>
      <td>**</td>
      <td>22</td>
      <td>13</td>
      <td>2</td>
      <td>14</td>
    </tr>
  </tbody>

</table>
<script>


var tableCtrl={
    handler:function(event){
         if(event.target.tagName=="TH"){
          var data=tableCtrl.data();
          var arr=tableCtrl.resort(data,event.target.cellIndex);
          tableCtrl.data(arr);
         }
    },
    data:function(data){
        if(typeof arguments[0]==="undefined"){
            var  table=document.getElementById('test');
            var  rows=table.rows;//包括thead
            var data=[];
            for(let i=0;i<rows.length;i++){
                     data[i]=[];
                for(let j=0;j<rows[i].children.length;j++){
                    data[i][j]=rows[i].children[j].innerText;
                }
            }
            return data;
        }
        else{
            var table=document.getElementById('test');
            var rows=table.rows;
             for(let i=0;i<data.length;i++){
                  for(let j=0;j<data[i].length;j++){
                    rows[i].children[j].innerText=data[i][j];
                  }
                  
             }
        }

    },
    resort:function(arr,sortBy){
        this.flag=!this.flag;
        var newarr=[];
         newarr=arr.slice(1).sort(function(a,b){
            return result=tableCtrl.flag? a[sortBy]-b[sortBy] : b[sortBy]-a[sortBy];
        }); 
        newarr.unshift(arr[0]); 
        return newarr;
    },
    flag:true
}
 var tableListener=document.getElementById('test').addEventListener('click',tableCtrl.handler);


</script>
发表于 2017-08-15 22:55:25 回复(0)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
	<title>sort</title>
</head>
<body>
<table>
	<Thead>
		<th id='name'>姓名</td>
		<th id='power'>力量</td>
		<th id='speed'>敏捷</td>
		<th id='smart'>智力</td>
	</Thead>
	<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>14</td>
	</tr>
	<tr>
		<td>流浪剑客</td>
		<td>23</td>
		<td>15</td>
		<td>14</td>
	</tr>
</table>
<script type="text/javascript">
    var flag=1;
    var objList=[];
    var trs=document.getElementsByTagName('tr');

    // console.log(trs.length);
    for(var i=1;i<trs.length;i++){
    	var tds=trs[i].children;
    	// var obj={};
    	var obj=[];
    	obj.push(tds[0].innerHTML);
    	for(var j=1;j<tds.length;j++){
    		obj.push(parseInt(tds[j].innerHTML));
    	}
    	objList.push(obj);
    }
    // console.log(objList);

	var theads=document.getElementsByTagName('Thead')[0];
	theads.onclick=function(){
		var event=event||window.event;
		var target=event.target||event.srcElement;
		switch(target.id){
			case 'name':   mySort(objList,0);break;
			case 'power':  mySort(objList,1);break;
			case 'speed':  mySort(objList,2);break;
			case 'smart':  mySort(objList,3);break;
			default: break;
		}
		flag=-1*flag;
		render();
	}
	function render(){

		for(var i=1;i<trs.length;i++){
			var tds_=trs[i].children;
			for(var j=0;j<tds.length;j++){
				console.log(i+':'+objList[i-1][j]);
				tds_[j].innerHTML=objList[i-1][j];
			}
		}
	}
	function mySort(arr,index){
		// var index_=index;
		arr.sort(function (v1,v2){
		// console.log('i:'+index);
		return flag*(v1[index]-v2[index]);		
	});
		console.log(arr);
		return arr;
	}

</script>
</body>
</html>

发表于 2017-04-27 16:14:21 回复(0)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
table{
border-top: 1px solid black;
border-left: 1px solid black;
}
table td{
border-right: 1px solid black;
border-bottom: 1px solid black;
}
</style>
</head>
<body>
<table>
<title>游戏人物</title>
<thead>
<tr>
<td>姓名</td>
<td>力量</td>
<td>敏捷</td>
<td>智力</td>
</tr>
</thead>
<tbody id="fa">
</tbody>
</table>
<script type="text/javascript">
var person = [
{name:"德鲁伊",strength:17,agile:24,intel:13},
{name:"月之骑士",strength:15,agile:22,intel:16},
{name:"众神之王",strength:19,agile:15,intel:20},
{name:"流浪剑客",strength:23,agile:15,intel:14}
];
function order(person){
var html = '';
var fa = document.getElementById('fa');
for(var i=0;i<person.length;i++){
html += `<tr><td>${person[i].name}</td><td>${person[i].strength}</td><td>${person[i].agile}</td><td>${person[i].intel}</td></tr>`
}
fa.innerHTML = html;
}
order(person);
var clicks = [0,0,0,0];
var heads = document.querySelectorAll('thead tr td');
for(var i = 1; i < heads.length;i++){
heads[i].index = i;
heads[i].clicks = 0;
heads[i].addEventListener('click',function(){
var clicks = this.clicks++;
if(this.index == 1){
person = person.sort(function(a,b){
if(clicks%2 == 0){
return a.strength - b.strength;
}else{
return b.strength - a.strength;
}

})
}else if(this.index == 2){
person = person.sort(function(a,b){
if(clicks%2 == 0){
return a.agile - b.agile;
}else{
return b.agile - a.agile;
}

})
}else if(this.index == 3){
person = person.sort(function(a,b){
if(clicks%2 == 0){
return a.intel - b.intel;
}else{
return b.intel - a.intel;
}

})
}
order(person);
})
}
</script>
</body>
</html>
发表于 2017-03-06 16:10:18 回复(0)
给tr第一行添加下面这个方法,并给第一行每列按顺序添加带0,1,2,3的id
function sort(obj){
var att = obj.getAttribute("isme");
var num = obj.id.match(/\d/g);
var tr = document.getElementsByTagName('tr');
var arr = [];
for(var i=1;i<tr.length;i++){
arr.push(tr[i].getElementsByTagName('td')[num].innerHTML);
}

if(att==1||att==null){

obj.setAttribute("isme",0);

var narr = arr.sort(function(a,b){return a.localeCompare(b)});

}else{

obj.setAttribute("isme",1);

var narr = arr.sort(function(a,b){return b.localeCompare(a)});

}
for(var i=0;i<arr.length;i++){

tr[i+1].getElementsByTagName('td')[num].innerHTML = arr[i];
}
}

编辑于 2016-12-12 14:12:00 回复(0)
可以参考datatables的源码有关排序的那一部分
发表于 2016-10-23 21:18:39 回复(0)