I read jquery basic tutorial a few days ago. When I saw the event delegate, I did not elaborate on the live () method, so I searched for live () and delegate.
Then, we can see that live () has been removed, deleted, and then checked the latest jq source code. It is removed. It is version 1.9.1 and I don't know live () which version was removed earlier? Sorry, I didn't pay attention to it before.
Looking at the source code, we found that both bind () and delegate () are implemented by on. On () is described as follows:
Copy codeThe Code is as follows:
. On (events [, selector] [, data], handler (eventObject ))
A simple event binding is similar to $ ('click'). on ('click', function () {}); and bind.
When you need to bind events to a large number of elements, event delegation is prioritized, which can bring performance benefits. For example:
For example, if you bind a click event to a document object, the click events of any elements on the page are bubbling to the document Object for processing.
Note that the second optional parameter in the description of. on () is selector. For example, if the second parameter is added, click:
Result:
When the event bubbles to the document object, the target of the event is detected. If it matches the input selector (button here), the event is triggered. Otherwise, the event is not triggered.
Note: on () can also receive an object parameter. The attribute of this object is an event type, and the attribute value is an event processing function. The following is an example of the official document:
Finally, the handler function of the original live () method is bound to the document object by default and cannot be changed. If the DOM nested structure is deep, event bubbling causes a high performance loss through a large number of ancestor elements. And use. On ()
Method, the event will only be bound$ ()
Function selector expression matches the element (in my example above, in order to simply bind to the document), you can precisely locate a part of the page, the overhead of event bubbling can also be reduced. Similarly, delegate () and on () are implemented using on: