<script type="text/javascript">
var tag=1;
function sortNumberAS(a, b)
{
return a - b
}
function sortNumberDesc(a, b)
{
return b-a
}
function SortTable(obj){
var td0s=document.getElementsByName("td0");
var td1s=document.getElementsByName("td1");
var td2s=document.getElementsByName("td2");
var td3s=document.getElementsByName("td3");
var tdArray0=[];
var tdArray1=[];
var tdArray2=[];
var tdArray3=[];
for(var i=0;i<td0s.length;i++){
tdArray0.push(td0s[i].innerHTML);
}
for(var i=0;i<td1s.length;i++){
tdArray1.push(td1s[i].innerHTML);
}
for(var i=0;i<td2s.length;i++){
tdArray2.push(parseInt(td2s[i].innerHTML));
}
for(var i=0;i<td3s.length;i++){
tdArray3.push(parseInt(td3s[i].innerHTML));
}
var tds=document.getElementsByName("td"+obj.id.substr(2,1));
var columnArray=[];
for(var i=0;i<tds.length;i++){
columnArray.push(parseInt(tds[i].innerHTML));
}
var orginArray=[];
for(var i=0;i<columnArray.length;i++){
orginArray.push(columnArray[i]);
}
if(obj.className=="as"){
columnArray.sort(sortNumberAS); //排序后的新值
obj.className="desc";
}else{
columnArray.sort(sortNumberDesc); //排序后的新值
obj.className="as";
}
for(var i=0;i<columnArray.length;i++){
for(var j=0;j<orginArray.length;j++){
if(orginArray[j]==columnArray[i]){
document.getElementsByName("td0")[i].innerHTML=tdArray0[j];
document.getElementsByName("td1")[i].innerHTML=tdArray1[j];
document.getElementsByName("td2")[i].innerHTML=tdArray2[j];
document.getElementsByName("td3")[i].innerHTML=tdArray3[j];
orginArray[j]=null;
break;
}
}
}
}
</script>
html部分,通过table的id来识别操作:
<table class="gridtable" width="859" align="center">
<tr>
<th width="357">aaa</th>
<th id="th1" onclick="SortTable(this)" class="as" width="142">bbbb</th>
<th id="th2" onclick="SortTable(this)" width="180" class="as">cccc<br/> <span style="color:red">点此排序</span></th>
<th id="th3" onclick="SortTable(this)" width="180" class="as">dddd<br/> <span style="color:red">点此排序</span></th>
<th id="th4" width="180" >eeee</th>
</tr>
CSS部分
table.gridtable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}