简体   繁体   中英

How to stop a onclick event when other button is clicked?

When the #terminateButton is clicked, I want #myButton to not show the alert when clicked and remove the onclick event. I tried to add removeEventListener but it did not work.

 let element = document.getElementById("myButton"); element.onclick = a document.getElementById("terminateButton").onclick = function () { element.innerHTML = "Does Nothing"; element.removeEventListener('click',a) }; function a(){ alert('You clicked the button'); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <button id='myButton'>Shows alert</button> <button id='terminateButton'>Dont show alert when other button clicked</button> <script src="script.js"></script> </body> </html>

You need to add your event listener with addEventListener function to be able to remove it with removeEventListener , like below. Here what mdn says:

The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target.

 let element = document.getElementById("myButton"); element.addEventListener("click", a) document.getElementById("terminateButton").onclick = function () { element.innerHTML = "Does Nothing"; element.removeEventListener('click', a) }; function a(){ alert('You clicked the button'); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <button id='myButton'>Shows alert</button> <button id='terminateButton'>Dont show alert when other button clicked</button> <script src="script.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM