简体   繁体   中英

Javascript : removeEventListener doesn't work

I have a first button where I add an event listener to execute foo function. The foo function just displays a number in console.

I have a second button for removing the event listener added.

Here the code, very simple :

<input type="button" value="Click here" id="button">

<input type="button" value="Remove Event Listener" onclick="removeEventListener();">

<script type="text/javascript">

number = 0;

//Function to display number in console :
function foo()
{
    number = number+1;

    console.log(number);    
}

//The button :
button = document.getElementById("button");

//Add event listener to the button :
button.addEventListener("click", foo);

//Function to remove event listener :
function removeEventListener()
{
    button.removeEventListener("click", foo);   
}

</script>

You can try it : https://jsfiddle.net/6m8z8qgn/

But when I click in the second button to remove the event listener, the event listener added to the first button is not removed, so console displays number again when I click in the first button.

An idea ? Thank you in advance, cordially.

change the name of the method removeEventListener to something else. Otherwise it is referred to javascript internal method.

function renameThis()

removeEventListener is a reserved keyword in JavaScript.

Try something else.

<input type="button" value="Remove Event Listener" onclick="anotherName();">
<input type="button" value="Click here" id="button">
<script type="text/javascript">

number = 0;

//Function to display number in console :
function foo()
{
number = number+1;

console.log(number);    
}

//The button :
button = document.getElementById("button");

//Add event listener to the button :
button.addEventListener("click", foo);

//Function to remove event listener :
function anotherName()
{
    button.removeEventListener("click", foo);   
}

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