Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>Save jQuery Objects in Variables for Reuse</h2> <p>Saving a jQuery object to a variable lets you reuse it without having to search back through the DOM to find it.</p> <p>(As @Louis suggested, I now use $ to indicate that a variable holds a jQuery object.)</p> <pre><code>// Bad: searching the DOM multiple times for the same elements $('div.foo').each... $('div.foo').each... // Better: saving that search for re-use var $foos = $('div.foo'); $foos.each... $foos.each... </code></pre> <p>As a more complex example, say you've got a list of foods in a store, and you want to show only the ones that match a user's criteria. You have a form with checkboxes, each one containing a criteria. The checkboxes have names like <code>organic</code> and <code>lowfat</code>, and the products have corresponding classes - <code>.organic</code>, etc.</p> <pre><code>var $allFoods, $matchingFoods; $allFoods = $('div.food'); </code></pre> <p>Now you can keep working with that jQuery object. Every time a checkbox is clicked (to check or uncheck), start from the master list of foods and filter down based on the checked boxes:</p> <pre><code>// Whenever a checkbox in the form is clicked (to check or uncheck)... $someForm.find('input:checkbox').click(function(){ // Start out assuming all foods should be showing // (in case a checkbox was just unchecked) var $matchingFoods = $allFoods; // Go through all the checked boxes and keep only the foods with // a matching class this.closest('form').find("input:checked").each(function() { $matchingFoods = $matchingFoods.filter("." + $(this).attr("name")); }); // Hide any foods that don't match the criteria $allFoods.not($matchingFoods).hide(); }); </code></pre>
    singulars
    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. 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