Two forms of jQuery each
June 22, 2010 19:09:07 Last update: June 22, 2010 19:09:50
The first form iterates over a jQuery object and executes a function for each matched element. This is an example from jQuery documentation:
The second form iterates over a general collection (examples from jQuery documentation):
<!DOCTYPE html> <html> <head> <style> ul { font-size:18px; margin:0; } span { color:blue; text-decoration:underline; cursor:pointer; } .example { font-style:italic; } </style> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> To do list: <span>(click here to change)</span> <ul> <li>Eat</li> <li>Sleep</li> <li>Be merry</li> </ul> <script> $("span").click(function () { $("li").each(function(){ $(this).toggleClass("example"); }); }); </script> </body> </html>
The second form iterates over a general collection (examples from jQuery documentation):
$.each([52, 97], function(index, value) { alert(index + ': ' + value); }); var map = { 'flammable': 'inflammable', 'duh': 'no duh' }; $.each(map, function(key, value) { alert(key + ': ' + value); }); $.each( { name: "John", lang: "JS" }, function(k, v) { alert( "Key: " + k + ", Value: " + v ); }); // or, equivalently jQuery.each( { name: "John", lang: "JS" }, function(k, v) { alert( "Key: " + k + ", Value: " + v ); });