html:
<div class="box">
<div><p>Hello World</p></div>
</div>
<input type="button" id="add" value="Add" />
jquery:
$(document).ready(function(){
var count = 0;
$("#add").click(function(){
$(".box").append('<div id="'+count+'"><button type="button" class="close">× </button></div>');
count++;
$(".close").click(function(){
alert("hi");
});
});
});
When I click on add the buttons are appended one after the other. When I click the first button of class close with id = 0, the alert box is appearing the number of times buttons are previously added.
I mean if I append 5 buttons and when I press close whose (id = 0) then the alert box is appearing 5 times.
if id = 1 , 4 times
id = 2 , 3 times
id = 3 , 2 times
id = 4, 1 time
If I put the JQuery close click function outside the JQuery add function then the alert box does not appear at all.
How do I get the alert box to appear only once whenever I press any close button?
Hope I explained it in a way others can understand, if not I’m sorry. Any help will be appreciated!
I think you simply need to unbind the close, for example:
So at your final code this should work fine for you:
});