使用LocalStorage单击X秒钟后,Vanilla Javascript禁用按钮,然后再次启用按钮

时间:2020-07-19 03:55:04

标签: javascript local-storage spam-prevention

您如何在香草javascript中而不是在jQuery中做类似的事情?

  1. 单击按钮可提交刷新/重定向到同一页面的表单
  2. 单击刷新页面后,按钮将被禁用
  3. localStorage将禁用的按钮存储X秒钟
  4. 经过X秒后,再次启用禁用的按钮
  5. 如果用户再次单击该按钮,请重复此过程

2 个答案:

答案 0 :(得分:1)

无法创建摘要,因为stackoverlow不允许访问localStorage,但:

<form onsubmit="handleSubmit(event)">
    <input type="text" id="target" />
    <input type="submit" value="submit"/>
</form>
<script>

  let disable = localStorage.getItem("disable");

  if(disable){
    console.log("5 second timeout");
    setTimeout(()=> {
      localStorage.removeItem("disable");
      disable = false;
      console.log("button enabled");
    },5000);
  }

  function handleSubmit(e) {
    e.preventDefault();
    if(disable){
      console.log("button is disabled"); 
      return;
    }
    localStorage.setItem("disable",true);
    location.reload();    
  }

</script>

编辑:类似以下内容的内容可以针对特定按钮进行修改

function handlerWrapper(e) {
    e.preventDefault();
    if(disable){
      console.log("button is disabled"); 
      return;
    }
    yourActualHandler(e); 
    localStorage.setItem("disable",true);
    location.reload();    
  }

答案 1 :(得分:0)

除了您提到的localStorage API之外,您所需要的只是按钮上的disabled属性和窗口对象上的setTimeout方法。

有关详细说明,请参见代码中的注释。

(注意:由于使用沙箱,使用localStorage的代码无法在SO代码段中运行,但是如果您希望看到它运行,则可以将其另存为html文件。)

<button id="refresh">Refresh</button>
<script>
  const refreshBtn = document.getElementById("refresh");
  refreshBtn.addEventListener("click", refresh);
  disable();

  function disable() {
    // If `disableRefresh` is truthy...
    if (localStorage.getItem("disableRefresh")) {
      // ...Disables the button and re-enables it after 2 seconds
      refreshBtn.setAttribute("disabled", ""); // Any value makes it true
      setTimeout(enable, 2000); // JavaScript measures times in milliseconds
    }
  }

  function enable() {
    // Removes (boolean) `disabled` attribute and (string) `disableRefresh` item
    refreshBtn.removeAttribute("disabled");
    localStorage.removeItem("disableRefresh")
  }

  function refresh() {
    // Sets `disableRefresh` to a truthy value, and refreshes the page
    localStorage.setItem("disableRefresh", "yep");
    location = location;
  };
</script>