简体   繁体   English

如何在HTML标签中显示Javascript函数?

[英]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的答案就是答案 (我在评论中写了相同的内容)。

But, I suggest another way: 但是,我建议另一种方式:

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 . myCount10时, if(myCount == 10) clearTimeout(_timeout)停止计时器。

Add Cell to a table: 将单元格添加到表中:

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/

See this fiddle 看到这个小提琴

You have to append the innerHTML each time you are performing the count. 每次执行计数时,都必须附加innerHTML。 So you have to set the innerHTML as below 所以你必须如下设置innerHTML

document.getElementById('main').innerHTML += countTotal + "<br />";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM