OK. I create an element, assign a click handler and add it to the body. Then I delete it and re-add, and the click handler no longer works.
Why is this going to happen.
var btn = $('<button>').text('hi').click(function(){console.log(3);}); var div = $('<div>'); div.append(btn); $('body').append(div); //click it now, it works.. div.html(''); div.append(btn); // now button doesn't work..
So why is this happening and what can I do to fix it.
Since it .html('')essentially matches .empty(), the following applies (from jQuery docs ):
.html('')
.empty()
To avoid memory leaks, jQuery removes other constructors from its children, such as data and event handlers, before deleting the elements themselves., ( ), .detach().
To avoid memory leaks, jQuery removes other constructors from its children, such as data and event handlers, before deleting the elements themselves.
, ( ), .detach().
.detach()
. button, , .
button
$(document).on('click', 'button', function () { // .. });
, .detach(), DOM, .
.detach() - , .remove(), , .detach() jQuery, . , DOM .
.remove()
div.find('button').detach(); div.append(btn);
div.append(btn); β btn = $('button').text('hi').click(function(){console.log(3);});
btn = $('button').text('hi').click(function(){console.log(3);});
, html() DIV, .
html()
html() , empty() .empty() .
empty()
, jQuery.cleanData , jQuery.removeEvent, .
jQuery.cleanData
jQuery.removeEvent
btn, , , html("").
btn
html("")
, detach() , , , , , , , .
detach()
FIDDLE
. , div html(''). , , jQuery jQuery.cleanData(getAll(elem, false));. data , . , .
div
html('')
jQuery.cleanData(getAll(elem, false));
data
, on ( ), -.
on
, , div, btn , .
. , detach. DOM, , .
detach
// remove element but keep its data btn.detach(); // append back div.append(btn);
html('').