javascript 極速 隱藏/顯示萬行表格列只需 60毫秒
2024-05-06 14:15:48
供稿:網友
隱藏表格列,最常見的是如下方式:
代碼如下:
td.style.display = "none";
這種方式的效率極低。例如,隱藏一個千行表格的某列,在我的筆記本(P4 M 1.4G,768M內存)上執行需要約 4000毫秒的時間,令人無法忍受。例如如下代碼:
代碼如下:
<body>
<input type=button onclick=hideCol(1) value='隱藏第 2 列'>
<input type=button onclick=showCol(1) value='顯示第 2 列'>
<div id=tableBox></div>
<script type="text/javascript"><!--
//--------------------------------------------------------
// 時間轉為時間戳(毫秒)
function time2stamp(){var d=new Date();return Date.parse(d)+d.getMilliseconds();}
//--------------------------------------------------------
// 創建表格
function createTable(rowsLen)
{
var str = "<table border=1>" +
"<thead>" +
"<tr>" +
"<th width=100>col1<//th>" +
"<th width=200>col2<//th>" +
"<th width=50>col3<//th>" +
"<//tr>" +
"<//thead>" +
"<tbody>";
var arr = [];
for (var i=0; i<rowsLen; i++)
{
arr[i] = "<tr><td>" + i + "1<//td><td>" + i + "2</td><td>" + i + "3<//td></tr>";
}
str += arr.join("") + "</tbody><//table>"; // 用 join() 方式快速構建字串,速度極快
tableBox.innerHTML = str; // 生成 table
}
//--------------------------------------------------------
// 隱藏/顯示指定列
function hideCol(colIdx){hideOrShowCol(colIdx, 0);}
function showCol(colIdx){hideOrShowCol(colIdx, 1);}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function hideOrShowCol(colIdx, isShow)
{
var t1 = time2stamp(); //
var table = tableBox.children[0];
var rowsLen = table.rows.length;
var lastTr = table.rows[0];
for (var i=0; i<rowsLen; i++)
{
var tr = table.rows[i];
tr.children[colIdx].style.display = isShow ? "" : "none";
}
var t2 = time2stamp();
alert("耗時:" + (t2 - t1) + " 毫秒");
}
//--------------------------------------------------------
createTable(1000); // 創建千行表格
// --></script>
遺憾的是,我們 google 出來的用 javascript 隱藏列的方式,都是采用這樣的代碼。
實際上,我們可以用設置第一行的 td 或 th 的寬度為 0 的方式,來快速隱藏列。
我們把 hideOrShowCol() 函數改為如下代碼:
代碼如下:
function hideOrShowCol(colIdx, isShow)
{
var t1 = time2stamp(); //
var table = tableBox.children[0];
var tr = table.rows[0];
tr.children[colIdx].style.width = isShow ? 200 : 0;
var t2 = time2stamp();
alert("耗時:" + (t2 - t1) + " 毫秒");
}
不過,僅這樣還達不到隱藏的效果,還需要設置 table 和 td 樣式為如下:
代碼如下: