开发者

JavaScript countdown

Why wont it countdown?

<script language="JavaScript" TYPE="text/javascript">
var container = document.getElementById('dl');
var seconds = 10;
var timer;
function countdown() {
seconds--;
if(seconds > 0) {
    container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
} else {
    container.innerHTML = '<a 开发者_开发技巧href="download.php">Download</a>';
    clearInterval(timer);
}
}
timer = setInterval(countdown, 1000);
</script>

<div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />


Try to move the <script> block after the <div id="dl"></div>.


This way, when document.getElementById('dl'); is executed, the corresponding element in the page will already exist.

With what you posted, when document.getElementById('dl'); is executed, the corresponding <div> is not there yet -- and, so, cannot be found.


Because you are trying to reach the element before it exists, as the code runs before the element is loaded.

Move the line that locates the element inside the function:

<script type="text/javascript">

var seconds = 10;
var timer;

function countdown() {
  var container = document.getElementById('dl');
  seconds--;
  if(seconds > 0) {
    container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
  } else {
    container.innerHTML = '<a href="download.php">Download</a>';
    clearInterval(timer);
  }
}

timer = setInterval(countdown, 1000);

</script>

<div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />


The setInterval takes a string to execute, not a function pointer.

timer = setInterval("countdown()", 1000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜