Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to use the "on()" method instead of "live()"? [duplicate]

I used live() for generated pages and frames. But in jQuery 1.9 this function is deprecated and does not work.

I use on() instead of live() but this method works for one time, and does not work in frames.

My code looks like this:

  $("#element").live('click',function(){     $("#my").html(result);    }); 

What is the solution?

like image 627
Morteza Avatar asked Feb 05 '13 09:02

Morteza


People also ask

What is the difference between on and live in jQuery?

on is a more streamline way of attaching events. Use of the . live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .

How to avoid event bubbling in jQuery?

stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

What is difference between BIND and live in jQuery?

In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.

What is .live in jQuery?

jQuery | live() MethodThis method is used to attach one or more event handlers for the selected elements. It also specifies the function that runs when the event occurs. The event handlers used will work for both current and future elements matching the selector.


1 Answers

$('body').on('click', '#element', function(){     $("#my").html(result); }); 

The clicked element selector is now passed through the .on() function parameters, and the previous selector should be replaced with the closest parent selector preferably with an ID. If you do not know what parent selector to use, body works too, but is less efficient.

see jQuery 1.9 .live() is not a function on how to migrate existing code.

like image 195
Samuel Liew Avatar answered Sep 25 '22 17:09

Samuel Liew