JQuery ReplaceWith() Function And Event Handlers In Memory
Say you have this html code : And you run this jQuery snippet: var button = $('#click-me'); button.on('click',
Solution 1:
Is the click event handler still exists somewhere in the memory? or, was it removed by the garbage collection process ?
No, the event never was bound it again because the function replaceWith
removed the complete DOM of the previous element button
.
You can use event delegation to keep that event "bound" it to the element #click-me
:
var button = $('#click-me');
$(document).on('click', '#click-me', function() {
console.log('Clicked !');
});
button.replaceWith('<button id="click-me" type="button">Click Me (Replaced)!</button>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-me" type="button">Click Me!</button>
Post a Comment for "JQuery ReplaceWith() Function And Event Handlers In Memory"