日期:2014-05-16 浏览次数:20382 次
<!doctype html > <html> <head> <title> new document </title> <script type="text/javascript"> var d1 = [[1,1],[2,2],[3,3]]; var d2 = [[11,1],[22,2]]; var d3 = [[1,11],[2,22],[3,33],[4,44]]; var Table = function(element){ this.element = document.getElementById(element); }; Table.prototype = { add : function(data){ var e = this.element, body = null; for(var i = 0; i < data.length; i++){ var tr = e.insertRow(); for(var j = 0; j < data[i].length; j++){ var td = tr.insertCell(); td.innerHTML = data[i][j]; tr.appendChild(td); } if(!body) body = e.getElementsByTagName("tbody")[0]; body.appendChild(tr); } }, update : function(data){ var e = this.element, len = e.rows.length, body = null; for(var i = 0; i < data.length && i < len; i++){ for(var j = 0; j < data[i].length; j++){ e.rows[i].cells[j].innerHTML = data[i][j]; } } if(i < len){ for(var n = len - 1; n >= i; n--){ e.deleteRow(n); } }else if(i < data.length){ this.add(data.slice(i)); } } }; window.onload = function(){ var n = 1, t = new Table("table1"); t.add(d1); document.getElementById("button1").onclick = function(){ if(n++ < 3){ t.update(window["d"+n]); } }; }; </script> </head> <body> <input type="button" id="button1" value="update" /><br/> <table id="table1"></table> </body> </html>
------解决方案--------------------
有多少条数据呢?
改用文档碎片添加,速度要快些。更新2000条在IE8下0.7秒,chrome 0.1秒左右。
<!doctype html > <html> <head> <title> new document </title> <script type="text/javascript"> var d1 = [[1,1],[2,2],[3,3]]; var d2 = [[11,1],[22,2]]; var d3 = [[1,11],[2,22],[3,33],[4,44]]; var Table = function(element){ this.element = document.getElementById(element); }; Table.prototype = { add : function(data){ var e = this.element, body = null, f = document.createDocumentFragment(); for(var i = 0, len = data.length; i < len; i++){ var tr = document.createElement("tr"); for(var j = 0; j < data[i].length; j++){ var td = document.createElement("td"); td.innerHTML = data[i][j]; tr.appendChild(td); } f.appendChild(tr); } body = e.getElementsByTagName("tbody")[0] || e; body.appendChild(f); }, update : function(data){ var e = this.element, len = e.rows.