The jQuery live() method attaches an event processing function to all matching elements. Even if the element is later generated through append, prepend, after and other events, it will still be valid.
This method can be seen as a variant of the .bind() method. When using .bind(), elements matched by the selector will have an event handler attached to them, while elements added later will not. You need to use .bind() again for this. For example:
<body>
<div class="clickme">Click here</div>
</body>
You can bind a simple click event to this element:
$(' .clickme').bind('click', function() { alert(
www.jb51.net); });
When an element is clicked, a warning box will pop up. Then, imagine that another element is added after this.
$('body').append('002fb57cb938b52f967f4f97e2f3a92cAnother target16b28748ea4df4d9c2150843fecfba68');
Although this new element will also match the selector ".clickme" , since this element is added after calling .bind() , clicking on this element will have no effect.
But live() provides a method for this situation. If we bind the click event like this:
$('.clickme'). live('click', function() { alert("
www.jb51.net"); });
In this way, clicking on the newly added element can still trigger the event handler.
Event delegation
The live() method works on an element that has not yet been added to the DOM due to the use of event delegation: event handlers bound to ancestor elements can respond to events triggered on descendants. The event handler passed to live() will not be bound to the element, but will be treated as a special event handler and bound to the root node of the DOM tree.
In our example, when a new element is clicked, the following steps occur:
1. Generate a click event and pass it to dc6dce4a544fdca2df29d5ac0ea9906b for processing.
2. Since there is no event handling function directly bound to dc6dce4a544fdca2df29d5ac0ea9906b, the event bubbles up to the DOM tree.
3. Events continue to bubble up to the root node of the DOM tree. This special event processing function is bound to it by default.
4. Execute the special click event handling function bound by .live().
5. This event processing function first detects the target of the event object to determine whether it needs to continue.
6. This test is implemented by testing whether $(event.target).closest('.clickme') can find matching elements.
7. If a matching element is found, the original event handler is called.
8. Since the test in step 5 above will only be done when the event occurs, elements added at any time can respond to this event.
The above is a detailed introduction to jQuery's jQuery live() method of adding event responses to dynamically generated content. I hope it will be helpful to everyone's learning.