JavaScript 中從外部函式中移除監聽器?


要從外部函式中刪除偵聽器,請使用 removeEventListener()。

示例

以下是程式碼 −

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<button id="demo">Press Me</button>
</body>
<script>
   var demoId = document.getElementById('demo');
   demoId.addEventListener('click', function fun() {
      outerFunction(this, fun);
   }, false);
   function outerFunction(self, funct) {
      console.log('outer function is called....');
      self.removeEventListener('click', funct, false);
      console.log("Listener has been removed...")
   }
</script>
</html>

要執行以上程式,請儲存檔名 anyName.html(index.html),然後右鍵單擊該檔案。在 VS Code 編輯器中選擇選項“使用即時伺服器開啟”。

輸出

這將生成以下輸出 −

單擊按鈕“按我”後。

這將在控制檯上生成以下輸出 −

更新於: 2020 年 10 月 24 日

69 次瀏覽

開始你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.