I’m binding a element with a click function when its added to the dom. My issue here is that if i add lets say 3 elements, and i click any of those it performs that function 3 times. what is it that makes it trigger those 3 times and could this be done any other way?
let me illustrate it with a jsfiddle demo here
html
<div id="breadcrumb"><a href="#" id="start" class="click-me">Start</a></div>
<a href="#" id="add_to_breadcrumb">Add to breadcrumb</a>
jquery
$('#add_to_breadcrumb').on('click', function(){
$('#breadcrumb').append('<a href="#" class="click-me">' + $('#breadcrumb > a').size() + '</a>', bindClick());
});
function bindClick(){
$(document).on('click', '.click-me', function(){
alert($(this).text());
});
}
Just try this:
DEMO
Binding
clickevent on each append, cause bind to each element again and again with each append.