在Javascript中使用For循环的innerHTML [英] innerHTML with For Loop in Javascript
问题描述
段标签中打印innerHTML中的表。这是有效的,但问题是当我点击提交按钮这个结果只显示最后一个值,如10 * 10 = 100,但我想运行完整我在代码中定义的循环从1到10.请解决此问题。
this is my coding. in this coding i want to print table in innerHTML in
paragraph tag.This is working but the problem is when i click submit button this result show only last value like this "10*10=100" but i want to run full loop which i define in code from 1 till 10. Please solve this issue.
<html>
<head>
<title>Table Program</title>
</head>
<body>
<input type="text" id="table" placeholder="Enter table"/>
<input type="button" value="Submit" onClick="table()"/>
<p id="demo"></p>
<!----------------------------------------------------------------------------------------------->
<script type="text/javascript">
function table()
{
var value = document.getElementById("table").value;
var demop = document.getElementById("demo");
var a;
for(a=1; a <= 10;++a)
{
demop.innerHTML=(value+"*"+ a +"="+ value*a);
}
}
</script>
</body>
</html>
推荐答案
for
循环每次执行时都会覆盖 demop
的innerHTML。
所以当你的 for
循环达到最后一次迭代时,
将是10,因此你只得到最后一个值10 * 10 = 100
Your for
loop is overwriting the innerHTML of demop
each time it is executing.
So when your for
loop reaches last iteration a
will be 10 and hence you only get the last value "10*10=100"
因此,每次迭代for循环时都应附加结果
只需将其设为这样
So you should append the result every time you iterate your for loop just make it like this
demop.innerHTML + =(value +*+ a +=+(value * a)+< br />);
所以你会在单独的行上得到你的输出。
So you will get your output on seperate lines.
这篇关于在Javascript中使用For循环的innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!