javascript 事件流的应用之 addEventListener

原始需求:防止按钮短时间内高频率触发点击事件,由于重复提交导致的业务异常。

图:

 

demo:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <style media="screen">
      .forbidden button{
        cursor: not-allowed;
      }
    </style>
  </head>
  <body>
    <h5>3秒内的多次点击只生效一次(基于事件拦截)</h5>
    <div class="button-group">
      <button class="link-button" onclick="randomNum()">random</button>
      随机数:<span id="random_num"></span>
    </div>
  </body>
  <script type="text/javascript">
  /* 初始化禁用绑定 */
  document.querySelector('.link-button').addEventListener('click',forbiddenButton,true);

  function randomNum(){
    document.querySelector('#random_num').innerHTML = Math.random();
  }

  var forbiddenTimer;
  function forbiddenButton(){
    var pNode = this.parentNode;
    pNode.classList.add('forbidden');
    pNode.addEventListener('click',function(e){
      if(Array.from(this.classList).includes('forbidden')) e.stopPropagation();
      _clearTimer();
    },true);
    _clearTimer();

    function _clearTimer(){/* 3秒之后取消禁用状态 */
      if(forbiddenTimer) clearTimeout(forbiddenTimer);
      forbiddenTimer = setTimeout(function(){
        pNode.classList.remove('forbidden');
      },3000);
    }
  }
  </script>
</html>

 

addEventListener事件拦截参考:https://www.cnblogs.com/Andyudd/p/5583563.html

 

posted @ 2018-07-11 17:51  【云】风过无痕  阅读(173)  评论(0编辑  收藏  举报