Why click event not work in this code (JSFiddle: http://jsfiddle.net/3WeP5/):
var holder = $("<div></div>");
$(document.body).append(holder);
var btn = $("<button>Click Here</button>");
btn.click(function(){alert('clicked');});
holder.append(btn);
holder.html("");
holder.append(btn);
you can replace this line:
btn.click(function(){alert('clicked');});
with (Not work again):
btn.bind("click",function(){alert('clicked');});
and if i dont use jquery and set javascript event like this, it works fine!!
btn[0].onclick=function(){alert('clicked');}
Why click event don`t work when i re-append element (button) and how can i fix it?
Look the documentation of .html()
:
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
holder.html("");
is removing the handler of the button. If you want to keep it you can use clone
as:
holder.append(btn.clone(true));
holder.html("");
holder.append(btn.clone(true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With