jQuery adds the event response jQuery live of method to dynamically generated content

  • 2020-09-16 07:21:36
  • OfStack

The jQuery live() method is to attach an event handler to all matched elements, even if the element is later generated by events such as append,prepend,after, etc.
This method can be viewed as a variation of the.bind () method. With.bind (), an event handler is attached to the element that the selector matches, and no element is added later. You need to use.bind () once more to do this. Such as:

<div class="clickme">Click here</div> 

You can bind this element to a simple click event:

$('.clickme').bind('click', function() { alert(www.ofstack.com); }); 

When the element is clicked, a warning box pops up. And then imagine 1 and then after that another element is added.
$('body').append('<div class="clickme">Another target</div>'); 

Although this new element also matches the selector ".clickme ", since this element was added after the.bind () call, clicking on this element has no effect.
But live() provides a way to do that. If we bind click events like this:
$('.clickme').live('click', function() { alert("www.ofstack.com"); }); 

This way, clicking on the new element still triggers the event handler.
Event delegation
The live() method is valid for an element that has not been added to DOM because of the use of event delegates: event handlers bound to ancestral elements can respond to events triggered on descendants. The event handler passed to live() is not bound to the element, but to the root node of the DOM tree as a special event handler.
In our example, when you click on a new element, the following steps occur in sequence:
1. Generate 1 click event and pass to < div > To deal with.
2, because there is no event handler directly bound in < div > So events bubble up into the DOM tree.
3. Events bubble up to the root node of the DOM tree, where this particular event handler is bound by default.
Execute the special click event handler bound by.live ().
5. The event handler first detects the target of the event object to determine whether it needs to continue.
6. This test is done by checking whether $(event.target).closest ('.clickme ') can find a matching element.
7. If a matching element is found, the original event handler is called.
8. Since the test is only done in Step 5 above when an event occurs, the element added at any time will respond to the event.
The above is a detailed introduction to the jQuery live() method of adding event response to dynamically generated content, hoping to help you learn.

Related articles: