zl程序教程

您现在的位置是:首页 >  后端

当前栏目

html中table数据排序的js代码

2023-06-13 09:14:29 时间
对了,注意那个innerText和innerHTML
复制代码代码如下:

functionsortCells(event){
varobj=event.target;
varcount=0;count是记录点击次数的,根据奇偶进行升序或降序
if(!obj.getAttribute("clickCount")){
obj.setAttribute("clickCount",0);
}else{
count=parseInt(obj.getAttribute("clickCount"));
count++;
obj.setAttribute("clickCount",count);
}
vartable=event.target.parentNode.parentNode;
if(table.nodeName.localeCompare("THEAD")==0){
if(table.parentNode.nodeName.localeCompare("TABLE")==0){
table=table.parentNode;
}else{
return;
}
}elseif(table.nodeName.localeCompare("TBODY")==0){
if(table.parentNode.nodeName.localeCompare("TABLE")==0){
table=table.parentNode;
}else{
return;
}
}elseif(table.nodeName.localeCompare("TABLE")==0){
}else{
return;
}
varcolNum;
for(x=0;x<table.rows(1).cells.length;x++){
if(event.target.innerText.localeCompare(table.rows(0).cells[x].innerText)==0){
colNum=x;
break;
}
}
varcolumn=table.rows(1).cells.length;
varrow=table.rows.length;
varAr=newArray(row-1);
for(x=0;x<row-1;x++){
Ar[x]=newArray(column);
}
for(x=1;x<row;x++){
for(y=0;y<column;y++){
Ar[x-1][y]=table.rows(x).cells(y).innerHTML;
}
}
     //这个可以对字符串进行本地化排序
/*if((count%2)==0){
Ar.sort(function(a,b){
returnb[colNum].localeCompare(a[colNum])
});
}else{
Ar.sort(function(a,b){
returna[colNum].localeCompare(b[colNum])
});
}*/
vartemp;
for(x=0;x<row-1;x++){
for(y=1;y<row-1;y++){
temp=Ar[y-1];
if((count%2)==0){
if(parseInt(Ar[y-1][colNum])>=parseInt(Ar[y][colNum])){
Ar[y-1]=Ar[y];
Ar[y]=temp;
}
}else{
if(parseInt(Ar[y-1][colNum])<=parseInt(Ar[y][colNum])){
Ar[y-1]=Ar[y];
Ar[y]=temp;
}
}
}
}
for(x=1;x<row;x++){
for(y=0;y<column;y++){
table.rows(x).cells(y).innerHTML=Ar[x-1][y];
}
}
count++;
}