Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are different costs, let's look at them:</p> <pre><code>$('#mybutton').live('click', function(e){ doSomething(); }); </code></pre> <p>There are 2 main costs here:</p> <ul> <li>The <code>#mybutton</code> selector needs to run immediately for no reason (the result is thrown away, we just wanted the selector anyway...we're binding to <code>document</code>). In this case it's an <a href="http://api.jquery.com/id-selector/" rel="nofollow"><code>#id</code> selector</a> so that's a very low cost...in other cases it's not cheap and very wasteful (for example <code>[attr=something]</code>).</li> <li>Every <code>click</code> that bubbles up to <code>document</code> now has to be checked against this selector, a per-click evaluation cost, this varies with the number of clicks you expect.</li> </ul> <hr> <p>Now let's look at the other method:</p> <pre><code>$('#mybutton').click(function(e){ doSomething(); }); </code></pre> <p>There are 2 main costs here as well:</p> <ul> <li>The <code>#mybutton</code> selector runs, but only once per ajax request. However, we're not wasting it, we're using the results.</li> <li>The <code>click</code> handler is bound to an actual element, rather than <code>document</code>, so there's a binding cost <em>each</em> time it runs, rather than once</li> </ul> <p>However, there's no per-click cost and the selector call itself isn't wasted...so it's better overall, <em>since you're using an ID</em>, this isn't true in other cases.</p> <hr> <p>In your case, since you're dealing with an ID (and guaranteed a single element), <strong>this is much cheaper</strong>:</p> <pre><code>$('#mybutton').click(function(e){ doSomething(); }); </code></pre> <p>In other cases, where you're binding hundreds of elements, <a href="http://api.jquery.com/live/" rel="nofollow"><code>.live()</code></a> is the clear winner, though <a href="http://api.jquery.com/delegate/" rel="nofollow"><code>.delegate()</code></a> would be even better. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload