日期:2014-05-16 浏览次数:20492 次
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>JS对象</title> </head> <body> <div id="moveId"> <label>表格行: <input name="textfield" type="text" size="10" id="tr" /> </label> 表格列: <input name="textfield2" type="text" size="10" id="td" /> <label> <input type="button" name="Submit" value="创建" id="btn"/> </label> </div> <script type="text/javascript"> function Table(tr,td){ this.tr = tr; this.td = td; } Table.prototype.createTable = function(){ var st=(new Date()).getTime(); var tableHTML = "<table width=\"100%\" border=\"1\">"; for(var i=0;i<this.tr;i++){ tableHTML += "<tr>" for(var j=0;j<this.td;j++){ tableHTML +="<td bgcolor='" + bgcl() +"'>"+ rand(1,15) +"</td>"; } tableHTML += "</tr>" } tableHTML +="</table>" var cid = document.createElement("div"); cid.innerHTML = tableHTML; document.body.appendChild(cid);//性能低部分 cid = null; var st2=(new Date()).getTime() - st; alert(st2); } var rand = function(value1,value2){ return Math.floor(Math.random()*(value2-value1+1)+value1); } var bgcl = function(){ var r,g,b; r = rand(0,255).toString(16); g = rand(0,255).toString(16); b = rand(0,255).toString(16); r = r.length<2?"0"+r:r; g = g.length<2?"0"+g:g; b = b.length<2?"0"+b:b; //alert(); return "#"+r+g+b; } var btn = document.getElementById("btn"), tr = document.getElementById("tr"), td = document.getElementById("td"); btn.onclick = function(){ var reg = /^[1-9]\d*$/; if(!reg.test(tr.value)||!reg.test(td.value)){ alert("数据不合格"); }else{ var table1 = new Table(tr.value,td.value); table1.createTable(); } } bgcl(); //alert(rand(1,15)); </script> </body> </html>
//我给你写一个随机颜色函数的高效版本 var bgcl0 = ['','00000','0000','000','00','0']; function bgcl(){ var s = (Math.random()*0x1000000|0).toString(16), n=s.length; return "#"+ (n==6 ? s : (bgcl0[n] + s)); }