Using live() - benefits - similar to bind()

前端 未结 3 1690
攒了一身酷
攒了一身酷 2020-12-15 11:07

I have been doing some reading up on jquery live event and am still kind of confused? What is the benefit to using it?

http://docs.jquery.com/Events/live

I k

相关标签:
3条回答
  • 2020-12-15 11:22

    Warning: This answer is old. Still very useful, but live has been deprecated and removed in newer versions of jQuery. So read the answer, because the use cases haven't changed, and you will learn why and when to use less event handlers. But unless you are still using a really old version of jQuery (v1.4.2 or prior), you should considerer writing the new equivalent code instead. As documented in the jQuery API for live and copied here:

    Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

    1. $( selector ).live( events, data, handler ); // jQuery 1.3+
    2. $( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
    3. $( document ).on( events, selector, data, handler ); // jQuery 1.7+

    Sometimes you have a set of elements when the page loads, like, say, edit links:

    <table>
      <tr>
        <td>Item 1</td>
        <td><a href="#" class="edit">Edit</a></td>
      </tr>
      <tr>
        <td>Item 2</td>
        <td><a href="#" class="edit">Edit</a></td>
      </tr>
      <tr>
        <td>Item 3</td>
        <td><a href="#" class="edit">Edit</a></td>
      </tr>
    </table>
    

    Now, maybe you have something like this with jQuery:

    $(document).ready(function() {
      $('a.edit').click(function() {
        // do something
        return false;
      });
    });
    

    But what if you add a new element to this table dynamically, after the page has initially loaded?

    $('table').append('
        <tr><td>Item 4</td><td><a href="#" class="edit">Edit</a></td></tr>
    ');
    

    When you click on "Edit" on this new Item, nothing will happen because the events were bound on page load. Enter live. With it, you can bind the event above like this:

    $(document).ready(function() {
      $('a.edit').live('click', function() {
        // do something
        return false;
      });
    });
    

    Now if you add any new <a> elements with a class of edit after the page has initially loaded, it will still register this event handler.

    But how is this accomplished?

    jQuery uses what is known as event delegation to achieve this functionality. Event delegation is helpful in this situation or when you want to load a large amount of handlers. Say you have a DIV with images:

    <div id="container">
        <img src="happy.jpg">
        <img src="sad.jpg">
        <img src="laugh.jpg">
        <img src="boring.jpg">
    </div>
    

    But instead of 4 images, you have 100, or 200, or 1000. You want to bind a click event to images so that X action is performed when the user clicks on it. Doing it as you might expect...

    $('#container img').click(function() {
        // do something
    });
    

    ...would then bind hundreds of handlers that all do the same thing! This is inefficient and can result in slow performance in heavy webapps. With event delegation, even if you don't plan on adding more images later, using live can be much better for this kind of situation, as you can then bind one handler to the container and check when it is clicked if the target was an image, and then perform an action:

    // to achieve the effect without live...
    $('#container').click(function(e) {
        if($(e.target).is('img')) {
            performAction(e.target);
        }
    });
    
    // or, with live:
    $('img', '#container').live('click', function() {
        performAction(this);
    });
    

    Since jQuery knows that new elements can be added later on or that performance is important, instead of binding an event to the actual images, it might add one to the div like in the first example (in reality, I'm pretty sure it binds them to the body but it might to the container in the example above) and then delegate. This e.target property can let it check after the fact if the event that was clicked/acted on matches the selector that you might have specified.

    To make it clear: this is helpful not only in the direct way of not having to rebind events, but it can be dramatically faster for a large amount of items.

    0 讨论(0)
  • 2020-12-15 11:25

    The benefit is that the event handler will also be added to new matching elements when those elements are created. This saves you from having to manually add the event handler every time you create a new element (matching a previously used selector) that needs it.

    Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element.

    From http://docs.jquery.com/Events/live#typefn, emphasis mine.

    0 讨论(0)
  • 2020-12-15 11:30

    Basically, with .live() you don't have to bother updating event handlers if you have a very dynamic web site.

    $('.hello').live('click', function () {
      alert('Hello!');
    });
    

    That example will bind the click event to any elements which already have the "hello" class as well as any elements that are dynamically inserted, be it by AJAX or by old-fashion JavaScript.

    0 讨论(0)
提交回复
热议问题