That's because the new element has no bound handlers, only the existing ones (the ones on the DOM before you called myFunction). Calling myFunction
again adds yet another handler, and so on.
Consider using delegation instead, where an existing ancestor holds the handler for the existing and future descendants. The nearer the ancestor, the better. That way, you call myFunction
only once.
In this example, the ancestor #wrap
holds the handlers for .options
. This will take effect for all existing and future .options
.
HTML:
<div id="wrap">
<input type="button" class="options" value="Option">
<input type="button" class="options" value="Option">
<input type="button" class="options" value="Option">
<input type="button" class="options" value="Option">
</div>
<input type="button" id="append_another_content" value="Append" />
JS:
$('#wrap').on('click', '.options', function () {
alert('Hello Friends!');
});
$('#append_another_content').click(function () {
$(this)
.siblings('#wrap')
.append('<input type="button" class="options" value="Option">');
});