Substitute methods after live have been removed from jQuery1.9+.

  • 2021-06-28 11:19:58
  • OfStack

According to the official description of jQuery, the live method has been deprecated in 1.7 and removed in 1.9.It is also recommended that the on method be used in future code instead.

The on method can accept three parameters: event name, trigger selector, and event function.

It is important to note that this trigger selector in the middle of the on method is the class name, id, or element name of the HTML element you want to add, which can be used to achieve the effect of live.

For example, I already have an div with id as parent in my html document. I will dynamically add another class as son within this div, and then I will bind an event for this span, so I need to write:


$('#parent').on('click','.son',function(){alert('test')});

This trigger selector is actually the $(e.target). is(selector) within JQ that determines an event parameter and only trigger object matching trigger selectors will trigger.This is done using the mechanism of event bubbling, which is also used by the original live, so there is no need for live to exist since it can be implemented by on, just to keep it alive from 1.7 to 1.9 for compatibility.

There's nothing left in this article, so let's use this feature to do something meaningful ~The dashed border of the A tag appears when the mouse is pressed in the lower version of IE, which is caused by focus.We can solve this problem just by doing a little bit of work in a global event.focus is not bubbling in modern browsers, but it can be in lower versions.Therefore, using live for focus in low-release browsers is effective.Prior to jQuery1.9 we could write as follows:


$("a").live("focus",function(){
this.blur();
}); 
jQuery1.9 Since then live It was deleted, so it should be written as follows: 
$(document).on("focus","a",function(){
this.blur();
}); 

Also note that if you change from live to on, don't forget to adjust the call chain.Because the return value of live is the object triggered by the event, using on is on the container object.


//jQuery1.9-
$("#panel").find("div").live("click",function(){
alert("x");
}).addClass("x");
//jQuery1.9+
$("#panel").on("click","div",function(){
alert("x");
}).find("div").addClass("x");  * 

Notice the last find ("div"), nothing else is wrong.

Here are the official instructions

http://jquery.com/upgrade-guide/1.9/#live-removed


Related articles: