|
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技术:一段效率很高的for循环语句使用方法,转载需保留来源!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。