Adding an element and deleting it destroys all event handlers in jquery?

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.

+4
source share
4 answers

Since it .html('')essentially matches .empty(), the following applies (from jQuery docs ):

To avoid memory leaks, jQuery removes other constructors from its children, such as data and event handlers, before deleting the elements themselves.

, ( ), .detach().

. button, , .

$(document).on('click', 'button', function () {
    // ..
});

, .detach(), DOM, .

.detach() - , .remove(), , .detach() jQuery, . , DOM .

div.find('button').detach();
div.append(btn);
+6

div.append(btn); β†’ btn = $('button').text('hi').click(function(){console.log(3);});

+2

, html() DIV, .

html() , empty() .
empty() .

, jQuery.cleanData , jQuery.removeEvent, .

btn, , , html("").

, detach() , , , , , , , .

FIDDLE

+2

. , div html(''). , , jQuery jQuery.cleanData(getAll(elem, false));. data , . , .

, on ( ), -.

, , div, btn , .

. , detach. DOM, , .

// remove element but keep its data
btn.detach();

// append back
div.append(btn);

html('').

+2

All Articles