Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why click event don`t work when re-append element?

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?

like image 649
Mehdi Yeganeh Avatar asked Dec 27 '22 00:12

Mehdi Yeganeh


1 Answers

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));
like image 139
Jonathan Naguin Avatar answered Jan 07 '23 01:01

Jonathan Naguin