简体   繁体   English

自动启用/禁用按钮

[英]Automatically Enable/Disable a button

I have a button(for asking questions) and countdown timer(where time="2017/04/30 10:30:00), now what I want is when time=reaches 0 automatically disable a button and when time is >0 automatically enable the button again. 我有一个按钮(用于询问问题)和倒数计时器(其中time =“ 2017/04/30 10:30:00),现在我想要的是当时间=达到0时自动禁用按钮,并且当时间> 0时自动再次启用该按钮。

I have only one variable for saving date var time="2017/04/30". 我只有一个变量可以保存日期var time =“ 2017/04/30”。 I guess constantly checking for time will be best option to make button enable/disable, but i do not know how to do it. 我想经常检查时间是使按钮启用/禁用的最佳选择,但是我不知道该怎么做。

It's not a good practice to do this in one's front-end script as almost anyone with a basic JavaScript knowledge can re-enable the button when time==0 which I assume you don't want to happen. 在一个前端脚本中执行此操作不是一个好习惯,因为几乎所有具有JavaScript基本知识的人都可以在time==0时重新启用按钮,而我认为您不希望发生这种情况。

I'll suggest doing this in one's server-side code. 我建议在服务器端代码中执行此操作。 In brief: 简单来说:

  1. check timer when generating the page, if timer is out, generate the disabled button without any code that was supposed to handle the click event. 在生成页面时检查计时器,如果计时器用完,则生成禁用的按钮,而没有任何应该用来处理click事件的代码。
  2. check timer when handling the request triggered by the button click, return 404 or other error message if timer is out. 在处理由按钮单击触发的请求时检查计时器,如果计时器超时,则返回404或其他错误消息。

All that being said, if you "have to" do this quick dirty way, you can simply use a setInterval or setTimeout : 话虽如此,如果您“必须”采取这种快速的肮脏方式,则可以简单地使用setIntervalsetTimeout

//javascript
// check timer every 200 ms
var TICK = 200; 
var checkTimerTask = setInterval(function(){
    if (getTimer() == 0){
        document.getElementById('buttonId').disabled = true; 
    } else {
        document.getElementById('buttonId').disabled = false;
    }
    // to stop checking uncomment the following line.
    // clearInterval(checkTimerTask);
}, TICK);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM