您的位置:首页 > Web前端 > JavaScript

面向对象的JavaScript的表格排序问题

2010-01-11 10:37 344 查看
JavaScript表格排序有很多种方式,不过在使用面向对象的方式进行JavaScript排序时IE会有一些问题。代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>演示表格的排序功能</title>
</head>

<script type="text/javascript">
var previousColumnIndex = 0;
ArrayUtil = {
arrayOne: [3, 32, 2, 5],
arrayTwo: ["3","32","2","5"],
demoNoarmal: function(){
this.arrayOne.sort();//默认方式排序
alert(this.arrayOne);
},
comparionAsc: function(one, two){ //升序
if(one < two){
return -1;
}else if(one > two){
return 1;
}else{
return 0;
}
},
comparionDesc: function(one, two){ //降升
if(one < two){
return 1;
}else if(one > two){
return -1;
}else{
return 0;
}
},
comparionSort: function(){
//this.arrayOne.sort(this.comparionAsc);
this.arrayOne.sort(this.comparionDesc);
alert(this.arrayOne);
},

comparionAscForString: function(one, two){
//return one.localeCompare(two); //升序
return -one.localeCompare(two); //降序
},
comparionString: function(){
this.arrayTwo.sort(this.comparionAscForString);
alert(this.arrayTwo);
},

compareTRs: function(trOne,trTwo){
/*var valueOne = trOne.cells[0].firstChild.nodeValue;
var valueTwo = trTwo.cells[0].firstChild.nodeValue;
return valueOne.localeCompare(valueTwo);*/
var vValue1 = trOne.cells[0].firstChild.nodeValue;
var vValue2 = trTwo.cells[0].firstChild.nodeValue;

if (vValue1 < vValue2) {
return -1;
} else if (vValue1 > vValue2) {
return 1;
} else {
return 0;
}
},

sortTable: function(){
var table = document.getElementById("tableSort");
var tBody = table.tBodies[0];
var columData = tBody.rows;
var trs = new Array;
// alert(columData.nodeType + columData.nodeName + columData.nodeValue);
for(var i = 0; i < columData.length; i++){
trs[i] = columData[i]; //对IE无效
//trs.push(columData[i]); //对IE有效,但是有问题
}
//对表格列内容排序
trs.sort(this.compareTRs);
var fragment = document.createDocumentFragment();
for(var i = 0; i < trs.length; i++){
//fragment.appendChild(trs[i]);
fragment.appendChild(trs.pop());//IE可以使用,但是有问题!!
}
//显示排序后的表格
table.appendChild(fragment);
}

};
</script>
<body>
<input type="button" value="默认排序方式" onclick="ArrayUtil.demoNoarmal()" />
<input type="button" value="比较排序方式" onclick="ArrayUtil.comparionSort()" />
<input type="button" value="字符串数组" onclick="ArrayUtil.comparionString()" />
<table border="1" id="tableSort">
<thead onclick="ArrayUtil.sortTable()" style="cursor:pointer">
<tr>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
</tr>
<tr>
<td>Johnson</td>
</tr>
<tr>
<td>Henderson</td>
</tr>
<tr>
<td>Williams</td>
</tr>
<tr>
<td>Gillaim</td>
</tr>
<tr>
<td>Walker</td>
</tr>
</tbody>
</table><br/>
<input type="button" value="表格排序" onclick="ArrayUtil.sortTable()" />
</body>
</html>

把以上代码拷贝到一个HTML文档,如果使用FixFox和Google浏览器都会正常显示,但是,如果使用IE来看,你会发现有非常奇怪的问题。本人现在还没有搞清楚为什么?对于IE,我非常郁闷!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: