JS2 for应用

for应用

 再谈js获取元素一二:

 var oUl=document.getElementById('list');      //静态方法


var oUl=document.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');         //动态方法

//aLi.length
除了通过ID获取DOM元素,其它方法的返回值是一个nodeList集合,举个例子:
window.onload=function(){
var aBtn=document.getElementsByTagName('input');
//alert(aBtn.length);
//创建多个按钮
document.body.innerHTML='<input type="button" value="按钮" /><input type="button" value="按钮" /><input type="button" value="按钮" />...<input type="button" value="按钮" />';
//逐个输出出来,或测试出来
aBtn[0].onclick=function(){alert(1);};
aBtn[1].onclick=function(){alert(2);};
aBtn[2].onclick=function(){alert(1);};
...

}; 

 我们会发现,重复执行某些代码,且每次执行的时候,有个数字在变化

 怎样解决呢?for循环

 for(var i=0;i<aBtn.length;i++){

   aBtn[i].onclick=function(){alert(i);};
}

执行步骤↓
1)var i
=0;
2)i<aBtn.length;  关键
3)括号里面的所有代码
4)i++

for帮我们解决了代码重复的问题,那么怎样才能提高它的性能呢?

1)不要直接和页面发生关系

运行下面两段代码,比较一下性能,例如:

window.onload = function (){

//1 直接和页面发生关系
    for( var i=0; i<6000; i++ ){
         document.body.innerHTML +
= '<input type="button" value="按钮" />';
        
    }
    

}; 

window.onload=function(){
 //不和页面直接发生关系
var str="";
for(var i=0;i<6000;i++){
str+
='<input type="button" value="按钮" />';
}
document.body.innerHTML=str;

}; 

for计算元素坐标 

 <!DOCTYPE HTML>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>

<style>
//注意要绝对定位噢!亲也可以尝试一下去掉绝对定位会发生什么
div 
{ width:50px; height:50px; background:red; position:absolute; top:0; left:0; font-size:30px; text-align:center; line-height:50px; color:#fff; }
</style>
window.onload=function(){
var aDiv=document.getElementsByTagName('div');
for(var i=0;i<11;i++){
    document.body.innerHTML+
='<div>'+i+'</div>';
}
for(var i=0;i<aDiv.length;i++){
aDiv[i].style.left
=10+i*50+'px';
aDiv[i].style.top=10+i*50+'px';
}
}
<script
>

</script>
</head>

<body></body>
</html>
原文地址:https://www.cnblogs.com/jill1231/p/5239127.html