Reputation: 363
I have script like this:
$(document).ready(function() {
$('.button').click(function() {
var button = document.createElement('button');
$(button).addClass('button');
$(button).html('Button');
$(button).appendTo('.container');
});
});
Example: jsfiddle
Buttons is created by button click hasn't click event. How to attach this event to have possibility to create buttons with using of any button?
Upvotes: 1
Views: 61
Reputation: 43166
You need to delegate the event handler to work with dynamically generated elements.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
You can use on()
method to delegate the handler as follows:
$(document).on("click",".button",function() {})
Upvotes: 4