一个按钮有两个功能

one button with two functions

本文关键字:两个 功能 一个 按钮      更新时间:2023-09-26

当我按下一次按钮时,我想开始计数,当我再次按下时停止计数。我知道用一个按钮点击事件来处理两个功能,它与";"是分开的。有什么建议吗?这段代码可以很好地使用两个按钮,每个按钮用于一个函数。提前谢谢。

<form>
<input type="button" value="Start count!" onclick="doTimer();stopCount();" />
</form>

javascript代码:

var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}

这样的东西怎么样:

onclick="handleClick();"

和你的JS:

function handleClick() {
  if (timer_is_on) {
    timer_is_on = false;
    clearTimeout(t);
  } else {
    timer_is_on = true;
    timedCount();
  }
}

这将一个接一个地调用,这毫无意义。

使用单个函数,检查标志的值,然后执行适当的操作。

这是我未经测试的解决方案,其中包含了一些技巧。

首先,我认为您可能可以去掉<form></form>标签。

其次,您可能会发现给变量取有意义的名称很有帮助,而不仅仅是ct

第三,将计时器更改为布尔值:var timer_is_on = false;

第四次将按钮更改为:<input type="button" value="Start count!" onclick="doTimer();" />

第五个用这个替换你的代码:

function doTimer(){
  if( timer_is_on ){
    // Code to start the timer
    // and any other code you want
    timer_is_on = false;
  }else{
    // Code to stop the timer
    // and any other code you want
    timer_is_on = true;
  }
}