According to the official description ofjQuery, the live method is no longer recommended in 1.7, anddeletedthis method in 1.9. And it is recommended to use the on method instead in future code.
The on method can accept three parameters:Eventname, trigger selector, and event function.
What needs special attention is: the trigger selector in the middle of the on method is the class name, id or element name of theHTML elementyou are about to add, use it You can achieve the live effect.
For example, myhtml documentalready has a p with the id of parent, and I will dynamically add a span with the class of son inside this p. Then I bind an event to this span, then I need to write like this:
$('#parent').on('click','.son',function(){alert('test')});
This trigger selector is actually $(e.target) that determines the event parameters once inside JQ ).is(selector), only the trigger object matching the trigger selector will trigger. This is done using the event bubbling mechanism. The original live also uses the bubbling mechanism, so since on can be implemented, there is no need for live to exist. It is just for compatibility that it has survived from 1.7 to 1.9. .
There is not much content in this article. Let’s use this function to do something meaningful and demonstrate it~ In the lower version of IE, the A tag will have a dotted border when the mouse is pressed. This is caused by focus. of. We can solve this problem as long as we do some tricks in the global event. Focus does not bubble in modern browsers, but it can bubble in older browsers. So it is effective to use live for focus in lower version browsers. In versions before jQuery1.9, we can write like this:
$("a").live("focus",function(){ this.blur(); });
After jQuery1.9, since live has been deleted, we should write like this:
$(document).on("focus","a",function(){ this.blur(); });
Also note that if you change from the live writing method to the on writing method, don’t forget to adjust the call chain. Because the return value of live is the object triggered by the event, and using on is on the container object.
//jQuery1.9-$("#panel").find("p").live("click",function(){ alert("x"); }).addClass("x");//jQuery1.9+$("#panel").on("click","p",function(){ alert("x"); }).find("p").addClass("x");
Pay attention to the last find("p"), there will be no other problems.
The above is the detailed content of Detailed introduction to alternative methods after live has been deleted in jQuery 1.9 and above versions. For more information, please follow other related articles on the PHP Chinese website!