I was reading "JQuery Basics Tutorial" a few days ago. When I saw event delegation, the live() method was not very detailed, so I searched about live() and delegate().
Then I saw that live() has been removed somewhere. Sorry, then I went to see the latest jq source code. Sure enough, it has been removed. It is now version 1.9.1. I don’t know where live() was before. Which version was removed? Sorry, I didn't notice it before.
Looking at the source code, I found that bind() and delegate() are both implemented by on(). The description of on() is as follows:
When you need to bind events to more elements, give priority to event delegation, which can bring performance benefits. For example:
As shown in the picture above, bind the click event to the document object. Click events that occur on any element on the page will bubble up to the document object and be processed.
Notice the second optional parameter in the description of .on(): selector. As shown below, a second parameter is added, selector button:
Result:
When an event bubbles up to the document object, detect the target of the event. If it matches the incoming selector (button here), the event will be triggered, otherwise it will not be triggered.
Note that .on() can also receive an object parameter. The attribute of the object is the event type, and the attribute value is the event processing function. Here is an example from the official documentation:
One final point is that the original live() method and processing function are bound to the document object by default and cannot be changed. If the DOM nested structure is very deep, event bubbling through a large number of ancestor elements will cause a large performance loss. . With the .on()
method, the event will only be bound to the element matched by the selector expression of the $()
function (in my example above, it is bound to the document for simplicity), so it can be accurately positioned on the page. part, and the overhead of event bubbling can also be reduced. delegate() is the same as on(), after all, it is implemented using on():