Why does the click do function not work when re-adding an item?

Why the click event does 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 (Does not work again):

 btn.bind("click",function(){alert('clicked');}); 

and if I don't use jquery and set a javascript event like this, it works fine !!

 btn[0].onclick=function(){alert('clicked');} 

Why does the click event not work when I add an element (button) again and how to fix it?

+4
source share
3 answers

See the .html() documentation :

When .html () is used to set the content of an element, any content that was in that element is completely replaced with the new content. In addition, jQuery removes other constructs, such as data and event handlers from children, before replacing these elements with new content.

holder.html(""); removes the button handler. If you want to save it, you can use clone as:

 holder.append(btn.clone(true)); holder.html(""); holder.append(btn.clone(true)); 
+6
source

Try on jQuery ON

 // You are better off just adding a id to the button var btn = $("<button id=\"someButton\">Click Here</button>"); $(document).on('click', '#someButton', function(){ alert('clicked'); }); 

What does this mean, add the click recipient to the document and when someone clicks on the document that he will check to see if there is event.target === btn

Here is a demo

The reason the event is not working is because jQuery.html(); removes event listeners, this is confirmed here https://github.com/jquery/jquery/blob/master/src/manipulation.js#L231

Jsfiddle

+3
source

Use event delegation :

 $(document.body).on('click', btn, function() { alert('clicked!'); }); 

Your code does not work, because when the script binds the function to this particular element on the first boot, but when you add another one, the script does not run again, and therefore the added element does not receive the event associated with it. When we add delegation delegation, we target document.body , and therefore, when the script event receives the loaded event, it binds to this element on the body .

Demo version

For earlier versions of jQuery, you can use this:

 $(document.body).delegate(btn, 'click', function() { alert('clicked!'); }); 
+1
source

Source: https://habr.com/ru/post/1491252/


All Articles