Common binding events and on delegate events in jQuery – jquery dynamically generates html onclick does not work

Take the click event as an example:

Normal binding event: $(‘.btn1’).click(function(){} binding

on binding event: $(document).on(‘click’,’.btn2′,function(){} binding

So what’s the difference between these two ways?

First let’s look at the difference in practice:

①The click event is after the page is loaded, all the elements with the class name btn1 are obtained, and then the click event is bound. If you generate another btn1 element through other operations, it will not have the click event;

②The on() event has the effect of monitoring, which can realize dynamic html element binding. For example, there is only one btn2 element at the beginning. You add another btn2 element by some method. This element can also be clicked, and btn2 can be added infinitely. .

So how to achieve this dynamic monitoring process?

The on() event is equivalent to $(document).click(function(){if(btn is clicked){}}), a click event is added to the document, the party clicks btn, the principle of event bubbling, from the inside Outside, it is equivalent to clicking on the document, then the following operations will be performed, which essentially only adds an event to the document, and the click() event adds a click event to all btn.

In addition on() event can add multiple events.

Advantages of on() delegated events: In the original event binding, many events need to be bound, and now only one event needs to be bound, which greatly improves the efficiency and page performance, and solves the bug that cannot be triggered by dynamically adding elements.

Jq1.7 began to support.

jQuery binding event method and difference (bind, click, on, live, one)

The first way:

$(document).ready( function (){
 $( "#clickme" ).click( function (){
 alert( "hello world click" )

The second way (the abbreviated way is the first):


The post Normal bind events and on delegate events inside jQuery – jquery dynamically generating html onclick not working issue first appeared on Lenix Blog .

This article is reprinted from
This site is for inclusion only, and the copyright belongs to the original author.