undefined

js的for循环

for应用:选取、生成、性能

方法1:document.body.innerHTML添加

使用这种方法添加多个元素的时候,性能不好。因为每一次添加元素的时候都要访问一次body

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>

<script>
window.onload = function (){
// 性能有问题!!!
for( var i=0; i<6000; i++ ){
document.body.innerHTML += '<input type="button" value="按钮" />';
}
};
</script>
</head>
<body>
</body>
</html>

方法2:只访问一次body

这个方法比上个方法,性能好很多,即使添加多个元素速度也很快

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>

<script>
window.onload = function (){
var str = '';
for( var i=0; i<6000; i++ ){
str += '<input type="button" value="按钮" />';
}
document.body.innerHTML = str;
};
</script>
</head>
<body>
</body>
</html>


小tips:可以利用循环来生成视频网站每个播放页面的每个第几集的按钮。

for循环生成坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!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>
<script>
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';
}

// 逢10 往下一行(小练习)
// 来一个小V字形(小练习)

};
</script>
</head>

<body>
</body>

</html>

for循环遍历二维数组,嵌套元素

觉得本站不错,请作者吃根辣条