为什么此JS倒数计时不起作用?

时间:2018-07-26 09:35:58

标签: javascript html countdown

<script type="text/javascript">
function countdown(seconds, element)
{
    var count = seconds;
    var counter= setInterval(timer, 1000);

    function timer()
    {
        count--;
        if (count <= 0)
        {
            clearInterval(counter);
            return;
        }   
        element.innerHTML = "Seconds remaining: " + count;
    }
}
</script>


<h1 onload="countdown(100, this)"></h1>

那为什么调用标签的innerHTML不变? 我看到了其他代码,但在这里没有看到任何错误。 我是JS编码的新手。

2 个答案:

答案 0 :(得分:1)

onload函数可以在<body>标记上使用,但似乎无法在其他标记上使用。尝试将其添加到<body>

function countdown(seconds, element)
{
  var count = seconds;
  var counter= setInterval(timer, 1000);
  function timer()
   {
     count--;
     if (count <= 0)
     {
      clearInterval(counter);
      return;
     } 
     element.innerHTML = "Seconds remaining: " + count;
     //console.log(count);
   }
}

h1List=document.getElementsByTagName("h1");
  for(i=0;i<h1List.length;i++){
     countdown(100-i*3, h1List[i]);
  }
//countdown(100, document.getElementsByTagName("h1")[0]);
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<!--<body onload="countdown(100,document.getElementsByTagName(`h1`)[0])">-->

答案 1 :(得分:0)

<script type="text/javascript">
function countdown(seconds)
{
var count = seconds;
var counter= setInterval(timer, 1000);

function timer()
{
count--;
if (count <= 0)
{
clearInterval(counter);
return;
}   
document.getElementById("timer").innerHTML = "Seconds remaining: " + count;
}}
</script>

<body onload="countdown(100)">
<h1 id="timer"></h1>
</body>

如果要在页面加载事件上运行计时器,请选中此复选框