[英]How to display Javascript function in an HTML tag?
I am trying to create a counting table for kids. 我正在尝试为孩子们创建一张计数表。 I want to display a button which will display the counting in a list.
我想显示一个按钮,它将在列表中显示计数。 I can get it to print to the page but i want to print it in paragraph tag in my HTML please have a look and suggest me the solution.
我可以将其打印到页面上,但是我想在HTML的段落标签中打印它,请看一下并向我建议解决方案。
<p id="main"></p>
<button onclick="counting();" >Counting 1 to 10</button>
var counting = function(){
var myCount = 1;
while(myCount < 11){
var countTotal = myCount;
document.getElementById('main').innerHTML = countTotal;
//print(countTotal);
myCount++;
}
return countTotal;
}
The @Lal's answer is the answer (I wrote the same in a comment). @Lal的答案就是答案 (我在评论中写了相同的内容)。
Instead of using the while
cycle you can use a setInterval
, in my opinion to create a counting table for kids the user experience is more important then performance: 在我看来,可以使用
setInterval
while
不是使用while
周期来为孩子创建一个计数表,用户体验比性能更重要:
take a look to this code: 看一下这段代码:
var counting = function(){
var myCount = 1;
document.getElementById('main').innerHTML += myCount + "<br/>";
var _timeout = setInterval(function(){
myCount++;
document.getElementById('main').innerHTML += myCount + "<br/>";
if(myCount == 10) clearTimeout(_timeout)
},1000)
}
This function set a timer that every 1000 milliseconds (1 second) show you a new number so as to allow time for the child to count. 此功能设置了一个计时器,该计时器每1000毫秒(1秒)向您显示一个新数字,以使孩子有时间进行计数。
Look this example: https://jsfiddle.net/Frogmouth/bke47w3u/2/ 看这个例子: https : //jsfiddle.net/Frogmouth/bke47w3u/2/
if(myCount == 10) clearTimeout(_timeout)
stop the timer when myCount
is 10
. 当
myCount
为10
时, if(myCount == 10) clearTimeout(_timeout)
停止计时器。
If you need to add the number like cell of table simply change the html container #main
: 如果您需要添加像表单元格这样的数字,只需更改html容器
#main
:
<table id="main"></table>
and the html printed by .innerHTML
: 和
.innerHTML
打印的html:
document.getElementById('main').innerHTML += "<tr><td>" + myCount + "</td></tr>";
This show you a table with 1 cell for each rows for a total of 10 rows. 这将显示一个表,每行有1个单元格,总共10行。
Example: https://jsfiddle.net/Frogmouth/bke47w3u/5/ 示例: https : //jsfiddle.net/Frogmouth/bke47w3u/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.