原生js之addEventListener,removeEventListener

使用addEventListener添加事件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <button type="button" id="btn">btn</button>
  <button type="button" id="btn2">btn2</button>
  <script>
    function f1() {
      console.log('我是第一个事件');
    };

    function f2() {
      console.log('我是第二个事件')
    }

    function my$(d) {
      return document.getElementById(d);
    };
    my$('btn').addEventListener('click',f1,false);
    my$('btn').addEventListener('click',f2,false);

    my$('btn2').onclick = function () {
      console.log('点击啦,我要注销一个事件哦');
      my$('btn').removeEventListener('click',f1,false);
    };

  </script>
</body>

</html>

  点击btn

点击btn2

点击btn

第一个事件已被移除

更多请参照这一文章

猜你喜欢

转载自www.cnblogs.com/gitByLegend/p/10863310.html