我想使用以下内容使代码只能通过按下按钮而不是在页面加载时自行启动代码来启动.还添加了一个重置按钮.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var interval;
var minutes = 5;
var seconds = 10;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
alert(el.innerHTML = "countdown's over!");
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? 'seconds' : 'second';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
seconds--;
}, 1000);
}
</script>
</head>
<body>
<div id='countdown'></div>
</body>
</html>
解决方法:
而不是onload使用这个
<input type="button" onclick="countdown('countdown');" value="Start" />
重置,使用此
<input type="button" onclick="minutes=5;seconds=10;" value="Reset" />