简体   繁体   中英

How can I remove a click event from an element in Javascript?

I have a <div> element that has a click event attached to it using the following code:

var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);

At a later point I copy the element and add it to another part of the DOM , but need to first remove the click event

var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);

I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.

Any ideas?

Move the anonymous click handler function out of the addEventListener call:

var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);

after which you should be able to:

var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);

The answer above is correct. However, in case, someone is looking to remove the onclick function which is attached to a button like this for eg

<button type="button" onclick="submit()" id="tour-edit-save">Save</button>

In this case, to remove the onclick attached function, one will have to remove the attribute onclick and that would work perfectly fine. Here is how you would remove using pure JavaScript

document.getElementById('tour-edit-save').removeAttribute('onclick');

Using jquery

$('#tour-edit-save').removeAttr('onclick');

Hope this helps someone who's looking for this answer.

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