Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách xóa trình nghe sự kiện với JavaScript


Dùng phương thức removeEventListener() trong JavaScript để xóa trình xử lý sự kiện gắn với addEventListener().

Ví dụ

<!DOCTYPE html> <html>    <head>       <style>          #box {             background-color: gray;             border: 2px dashed;          }       </style>    </head>    <body>       <div id="box">Văn bản demo!          <p>Nhấn dưới để xóa trình xử lý sự kiện.</p>          <button onclick="removeEvent()" id="btnid">Xóa</button>       </div>       <p id="pid"> </p>       <script>          document.getElementById("box").addEventListener("mousemove", display);          function display() {             document.getElementById("pid").innerHTML = Math.random();          }          function removeEvent() {             document.getElementById("box").removeEventListener("mousemove", display);          }       </script>    </body> </html>