几种隐藏表格列的方法
xmliy 2008-06-24 10:48:19 最近在处理一个大的数据表格(有一、两千行)的时候,对几种隐藏表格列的方法进行了比较。
先建立一个测试表格:
<style>
.Column0: { display: inherit; }
.Column1: { display: inherit; }
.Column2: { display: inherit; }
.Column3: { display: inherit; }
.Column4: { display: inherit; }
.Column5: { display: inherit; }
.Column6: { display: inherit; }
.Column7: { display: inherit; }
.Column8: { display: inherit; }
.Column9: { display: inherit; }
</style>
<script type="text/javascript">
var myTable = document.createElement("div");
myTable.border = 1;
for(var i = 0; i < 1000; i++)
{
var myRow = myTable.insertRow();
myRow.id = "row_" + i;
for(var j = 0; j < 10; j++)
{
var myCell = myRow.insertCell();
myCell.id = "cell_" + i + "_" + j;
myCell.className = "Column" + j;
myCell.innerText = i + "," + j;
}
document.body.appendChild(myTable);
}
</script>
假设要隐藏表格中的第5行,采用如下几种方法进行比较:
1、遍历表格中的每一行
for(var i = 0, count = myTable.rows.length; i < count; i++)
{
myTable.rows(i).cells(4).style.display = "none";
}
2、利用单元格的名称
for(var i = 0, count = myTable.rows.length; i < count; i++)
{
document.all("cell_" + i + "_4").style.display = "none";
}
3、利用eval
for(var i = 0, count = myTable.rows.length; i < count; i++)
{
eval("cell_" + i + "_4.style.display = 'none'");
}
4、直接修改<style>中的式样
document.styleSheets[0].rules[4].style.display = "none";
在IE7.0下测试,执行效率:第一种方法与第二种方法差不多,都比较慢;第三种方法比起前两种更慢;第四种方法最快,几乎是在瞬间完成。