JQuery.live () Handlers that run multiple times

I need to generate some buttons dynamically based on some service response, and also apply some handlers when these buttons are clicked. So I use jQuery.live() for this, it works well for the first time.

But when I delete all the buttons using jQuery("<some container div>").empty() and creates these buttons again, now when I click the "call the handler twice" button, if I repeat the same thing, it starts three times and so same.

Can you guys help me, thanks in advance.

+4
source share
4 answers

$ (). live () was depreciated in jQuery 1.7 and removed in 1.9

Or try something like

 $('#button').die('click').live('click', function(e) { alert('Button click'); }); 
+9
source

Follow the jQuery jquery.live () website:

Attach an event handler for all elements that match the current selector, now and in the future .

This means: the event that you attach using live will be applied to all elements that have the same selector. Therefore, you should check the event of the element and simply attach a new element if it is not available.

 $("SELECTOR").live('click',function(e){ //check the event is already set e.preventDefault(); if(e.handled === true) return false; e.handled = true; //Do something here //YOUR CODE HERE return false; }); 
+3
source

Try this using the removeButton function, try to cancel the click event. And reinstall it when you add it again.

 function removeButton(){ $("button").unbind("click"); //code for removing button } function addButton(){ //code for adding button $("button").live("click", function(){ //your code }); } 
0
source

This is not a direct answer to the question. However, it is worth paying attention to this.

.live () vs .bind ()

@jAndy says:

You should consider using .delegate () instead of .live () whenever possible. Since event delegation for .live () is always aimed at the body / document, and you can limit bubbling with .delegate ().

And from jQuery :

As in jQuery 1.7, .delegate() been replaced with the .on() method. However, for earlier versions .delegate() remains the most efficient way to use event delegation.

Link

0
source

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


All Articles