click handler remains after deleting element and perform its actions multiple times
I am dynamically adding a custom component with buttons this way
function showPopup(){
var comp = '<div id="alert"><input type="button" id="proceed"><input type="button" id="close"></开发者_运维技巧div>';
$('#body').append(comp);
}
To these buttons I have handlers like this
$('#close').live('click',function(){
$(this).parent().remove();
});
$('#proceed').live('click',function(){
//ajax-call
});
Now the issue is when I call the function say n times and close it and when i do a proceed now it does n ajax calls. Any solution to this ? Thank you
You are adding multiple elements with the same id
which is invalid markup. This will be causing problems for jQuery when it comes to delegating the event to the correct element. jQuery matches exactly one element when querying for an ID - see Does duplicate id's screw up jquery selectors?
Also, this demo seems to be working for me in Chrome 14.
It's hard to tell for sure because you don't have the live
calls in context but I assume that the calls to live
are within some code that is called multiple times. If so, this is the problem. live
should only be called once for each element. live
will then automatically apply to all items created matching the selector. If it is called multiple times you will attach another handler each time.
精彩评论