js innerHTML的循环问题
<!DOCTYPEhtml><html><body><p>点击下面的按钮,将代码块循环五次:</p><buttononclick="myFunction()">点击这里<...
<!DOCTYPE html>
<html>
<body>
<p>点击下面的按钮,将代码块循环五次:</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
for (var i=0;i<5;i++){
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
我的问题是,为什么document.getElementById("demo").innerHTML=x;这行代码在循环外,可是却同样执行5次呢?
运行结果:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4 展开
<html>
<body>
<p>点击下面的按钮,将代码块循环五次:</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
for (var i=0;i<5;i++){
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
我的问题是,为什么document.getElementById("demo").innerHTML=x;这行代码在循环外,可是却同样执行5次呢?
运行结果:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4 展开
2个回答
展开全部
x=x + "The number is " + i + "<br>";
这段代码中x的值在累加拦正,当你循环五次后x的值就变为
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
最后打出的是x的值,而你又赋值给innerHTML,所以打印出这结果,而不是document.getElementById("demo"简毁悔).innerHTML=x;这段代码循环了余碰五次
这段代码中x的值在累加拦正,当你循环五次后x的值就变为
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
最后打出的是x的值,而你又赋值给innerHTML,所以打印出这结果,而不是document.getElementById("demo"简毁悔).innerHTML=x;这段代码循环了余碰五次
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |