我的代码如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Demo</title>
<style type="text/css">
#submitbox .button{
padding:3px 6px;
background:#B4D666;
border-top:1px solid #B4D666;
border-right:1px solid #81B840;
border-bottom:1px solid #81B840;
border-left:1px solid #B4D666;
color:#2970A6;
font-size:11px;
cursor:pointer;
}
#submitbox .disabled-button{
background: #CCCCCC;
border-color: #CCCCCC #999999;
color: #CC6600;
}
</style>
</head>
<body>
<form name="form1" method="post" action="#">
<input name="counter" id="counter" value="enable" type="text" /> <br/><br/>
<div id="submitbox">
<input id="cmt-submit" type="button" class="button" value="Submit comment" onclick="return timer();" />
</div>
<script type="text/javascript">
<!--
//
var cmtSubmit = document.getElementById('cmt-submit');
var count = document.getElementById('counter');
var milisec = 0;
var seconds = 10;
var timercmt = 0;
var timertxt = 0;
function display() {
if (milisec <= 0) {
milisec = 9;
seconds -= 1;
}
if (seconds <= -1) {
milisec = 0;
seconds += 1;
}
if (seconds == 0) {
cmtSubmit.value = "Submit comment";
cmtSubmit.disabled=false;
cmtSubmit.className = "button";
clearTimeout(timercmt);
}
else {
milisec -= 1;
cmtSubmit.value = seconds + " sec wait before next comment";
cmtSubmit.disabled = true;
cmtSubmit.className = "disabled-button";
timercmt = setTimeout("display()", 100);
}
}
function timer() {
if (count.value == "enable") {
count.value = "disable";
timertxt = setTimeout("setCounter()", 10000);
return true;
}
else
{
clearTimeout(timertxt);
display();
count.value == "enable"
return false;
}
}
function setCounter() {
count.value == "enable"
}
-->
</script>
</form>
</body>
</html>
它仅适用于首次运行时的hix hix。
谁能看到我要去哪里错了?
最佳答案
找到它:您忘记了重新初始化变量。更新后的代码如下:
<script type="text/javascript">
<!--
//
var cmtSubmit = document.getElementById('cmt-submit');
var count = document.getElementById('counter');
var milisec = 0;
var seconds = 10;
var timercmt = 0;
var timertxt = 0;
function display() {
if (milisec <= 0) {
milisec = 9;
seconds -= 1;
}
if (seconds <= -1) {
milisec = 0;
seconds += 1;
}
if (seconds == 0) {
cmtSubmit.value = "Submit comment";
cmtSubmit.disabled = false;
cmtSubmit.className = "button";
clearTimeout(timercmt);
//--- You have to re--initialize variables here
milisec = 0;
seconds = 10;
timercmt = 0;
timertxt = 0;
}
else {
milisec -= 1;
cmtSubmit.value = seconds + " sec wait before next comment";
cmtSubmit.disabled = true;
cmtSubmit.className = "disabled-button";
timercmt = setTimeout("display()", 100);
}
}
function timer() {
if (count.value == "enable") {
count.value = "disable";
timertxt = setTimeout("setCounter()", 10000);
return true;
}
else
{
clearTimeout(timertxt);
display();
count.value == "enable"
return false;
}
}
function setCounter() {
count.value == "enable"
}
-->
</script>