首页 > 解决方案 > 截止日期后如何禁用javascript中的提交按钮

问题描述

如何在截止日期后禁用 JavaScript 中的提交按钮。

请我需要提交一个按钮,以便在截止日期后带走,或者返回一个截止日期已过的警报。

谢谢

<body>
  <h2>Welcome! </h2>
  <p>Please find below your responsibilities for the month</p>

  <div class=t ask> Task 1 </div>
  <p>Please Submit your report in the space below</p>
  <h3 style="color: red"> DEADLINE: 20/04/2020</h3>
  <form>
    <textarea>
    </textarea> <br> <br>
    <button>Submit</button>
  </form>
</body>

标签: javascriptformsbuttonexpired-sessionsdeadlines

解决方案


您可以使用windows.setTimeout调用来触发事件以隐藏提交按钮。要计算此事件应该发生的未来毫秒数,请创建一个Date包含日期的对象4/20/2020和一个包含当前日期的第二个Date对象。然后调用getTime()这两个对象。该函数定义为:

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

这两个值之间的差异是未来4/20/2020 12:00:00 AM发生的毫秒数,应该是调用的参数window.setTimeout。对于以下演示,在完成此计算后,计算值将被 10,000 毫秒覆盖。用于演示目的:

document.addEventListener('DOMContentLoaded', function(event) {
  let deadline = new Date(2020, 4, 20); // at 12:00 AM
  let now = new Date(); // current date and time
  let milliseconds = deadline.getTime() - now.getTime();
  milliseconds = 10000; // set to 10 seconds for testing purposes
  let submit = document.getElementById('submit');
  if (milliseconds > 0) {
    window.setTimeout(function() {
      submit.style.display = 'none';
    }, milliseconds);
  }
  else {
    submit.style.display = 'none';
  } 
});
<body>
  <h2>Welcome! </h2>
  <p>Please find below your responsibilities for the month</p>

  <div class=t ask> Task 1 </div>
  <p>Please Submit your report in the space below</p>
  <h3 style="color: red"> DEADLINE: 20/04/2020</h3>
  <form>
    <textarea>
    </textarea> <br> <br>
    <button id="submit">Submit</button>
  </form>
</body>

开发者发表的评论应该被认真对待。您还应该在服务器端进行检查,以检查表单是否在4/20/2020 12:00:00 AM使用适当的时区时或之后提交。在客户端,我们使用的是本地时区,但两个日期之间的毫秒数差异应该在某种程度上与时区无关,尽管可能存在细微差异。

如果您想精确计算到期的毫秒数,您可以使用:

let deadline = new Date(2020, 4, 20).toLocaleString("en-US", {timeZone: "America/New_York"});
deadline = new Date(deadline);
let now = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
now = new Date(now);

当然,您可以使用适合您的应用程序的任何时区。请注意,在分配之后,deadline = new Date(2020, 4, 20).toLocaleString("en-US", {timeZone: "America/New_York"});您最终会得到一个Date没有getTime功能的对象,因此需要从中构造一个新Date对象。


推荐阅读