Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() - Practical uses?

Tags:

jquery

I am working on trying to better understand the jQuery.each() method. Here's an example I came up with, not very practical, but it performs an action on each selected item from the selected set of elements returned:

// Loop over each link. $( "#links a.number" ).each(  // For each number, run this code. The "intIndex" is the  // loop iteration index on the current element. function( intIndex ){  // Bind the onclick event to simply alert the iteration index value.     $( this ).bind ("click", function(){         alert( "Numbered index: " + intIndex );     }); }); 

What are some examples of practical uses of the .each method you are using in your code? What exactly does $(this) represent?

like image 890
RedWolves Avatar asked Apr 06 '09 19:04

RedWolves


People also ask

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can we use forEach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

Is jQuery each slow?

This article (#3) ran some performance tests and found that the jQuery . each function was about 10x as slow as the native javascript for loop. Using Firebug, it's possible to measure the time each of the two functions takes to run.

Is forEach JavaScript or jQuery?

forEach() Method. The . forEach() method of JavaScript executes a given function once for each element of the array.


1 Answers

Note there are two types of jQuery's each, the one iterates over and returns jQuery objects, the other is a more generic version.

Core/each
Example: Create a csv of all the hrefs on the page. (iterates over matching DOM elements and 'this' reffers to the current element)

 var hrefs = "";   $("a").each(function() {       var href = $(this).attr('href');      if (href != undefined && href != "") {          hrefs = hrefs + (hrefs.length > 0 ? "," + href : href);      }  });   alert(hrefs); 

Utilities/jQuery.each
Iterating over an array or the elements of an object: (via: jQuery Documentation)

$.each( { name: "John", lang: "JS" }, function(i, n){   alert( "Name: " + i + ", Value: " + n ); });  $.each( [0,1,2], function(i, n){   alert( "Item #" + i + ": " + n ); }); 
like image 150
missaghi Avatar answered Sep 18 '22 06:09

missaghi