Reputation: 147
Why after use the .empty() method, the click event doesn't work anymore?
$(document).ready(function(){
var a = "<button>click</button>";
$("p").append(a);
$("button").click(function(){
alert("ok");
$("p").empty();
// it disappears
$("p").append(a);
// it reappears but if I click it again it doesn't work
});
});
...
<p></p>
Since I have a program with a button created globally and I have to place it and remove it frequently, but after the first use, nothing happens.
var checkAnswer = $("<button>",
{
text: 'Check',
click: function () {
// do something
}
});
Upvotes: 1
Views: 67
Reputation: 707836
Static event handlers are attached to a specific DOM element. If you remove that DOM element (which you are doing with .empty()
and create a new DOM element (which you are doing with .append()
, the original event handler attached to the now removed DOM element is gone.
In jQuery, it feels like you are attaching an event to a selector, but when you use the static form of .on()
or .click()
(like you are), the selector is evaluated once when you initially install the event handler. That selector turns into a list of DOM elements and those DOM elements at that specific time get the event handler attached to them. If you later create new DOM elements that also match that selector, they won't have any event handlers on them.
Delegated event handling can be used to solve this issue for some types of events.
Your options are:
If you want to read more about delegated event handling, here are some other answers that explain it:
Does jQuery.on() work for elements that are added after the event handler is created?
jQuery .on does not work but .live does
jQuery .live() vs .on() method for adding a click event after loading dynamic html
JQuery Event Handlers - What's the "Best" method
Upvotes: 4