给表格的每行加上样式,注意for的第二个参数,当数组下标越界时,row=row[i]返回false,到此循环结束。 var rows = document.getElementsByTagName('tr'); for( var i = 0, row; row = rows[i]; i++ ) { row.className = 'newclass'; } 测试代码: <!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>无标题文档</title> <style> li { margin-left:28px;} .abc {background-color:#eee;font-size:14px; margin-bottom:10px;} </style> <SCRIPT LANGUAGE="JavaScript"> <!-- function a(){ var row = document.getElementsByTagName("li"); var t1 = new Date(); for (var i=0,j; j=row[i]; i++) { j.className="abc"; } var t2 = new Date(); alert("耗时 "+(t2-t1).toString()+" 毫秒"); } function b(){ var row = document.getElementsByTagName("li"); var t1 = new Date(); for (var i=0; i<row.length; i++) { row[i].className="abc"; } var t2 = new Date(); alert("耗时 "+(t2-t1).toString()+" 毫秒"); } function c(){ var j="<ol>"; for (var i=0; i<2000; i++) { j=j+"<li>测试文字</li>"; } j=j+"</ol>"; document.getElementById("box").innerHTML = j; } //--> </SCRIPT> </head> <BODY> <input type="button" value="CreateTable" onclick="c()" /> <input type="button" value="Test old method!" onclick="b()" /> <input type="button" value="Test new method!" onclick="a()" /> <input type="button" value="Clear" onclick="document.getElementById('box').innerHTML='';" /> <div id="box"></div> </BODY> </HTML>
推荐阅读
不错的Javascript表格翻页效果
表格翻页
body, td{
font-size: 9pt;
}
a:link {
color: #FF0000;
}
a:visited {
color: #FF0000;
}
a:hover {
color: #006600;
}
共 6 页 当前第 1 页
第一页>>>详细阅读
本文标题:一段效率很高的for循环语句使用方法
地址:http://www.17bianji.com/kaifa2/JS/30196.html
1/2 1