lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call
$('a.pep').click()lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)You should lever the DOM event bubbling model to handle this. jQuery helps you with the
onmethod:See a working jsFiddle.
Note that I have removed the
valcall, becauseaelements can’t have a value… Note also that theonmethod is introduced in jQuery 1.7; before that, usedelegate: