The jQuery library provides a method, Each(), which will loop through each element of the target jQuery object:
Launch code in new window » Download code as text file »
While there is nothing revolutionary going on here (although the "Bind" method is freakin' sweet-ass-sweet unto itself), the beauty of the Each() method is that it creates a separate function scope for each loop iteration. For anyone who has tried to do a standard FOR-Loop in which each iteration tries to dynamically set some object value, you probably have run into situation where all values post-loop are the same. This has to do with when the variable is being bound.
By creating a separate function scope for each loop iteration, you basically eliminate all the "unexpected" variable binding behavior. Sweet! It seems every time I step back and look at what jQuery is doing for me, it's simply stripping away more and more headache time.
Download Code Snippet ZIP File
Comments (5) | Post Comment | Ask Ben | Permalink | Other Searches | Print Page
jQuery And Ext Partner To Deliver Integrated JavaScript And UI Features
Completely Awesome: Whack Your Boss
Yes indeed, each() rules. If you get excited about this kind of stuff, you may want to take a look at Ruby on Rails if you haven't already done so. You'll get excited about a lot of things. For one, the Ruby language alone has some very powerful features that are quite unique and that allow for very elegant code. I really like ColdFusion, but I think RoR brings a lot to the table and it costs nothing (OK, I know, our time is valuable) to give it a try and see something different. And if you decide to do so, please be sure to let us all know what you thought!
Posted by Thomas Messier on Feb 19, 2007 at 9:40 PM
Thomas,
Thanks for the heads up. To date, I have not looked into Ruby on Rails. However, I have heard a lot of good things about it. When I start to look into it, I am sure I will have a lot to say ;)
Posted by Ben Nadel on Feb 19, 2007 at 11:30 PM
Great Code.
Thanks
Posted by Matt on Mar 22, 2007 at 6:00 AM
exactly what i was looking for. this should be a jquery tutorial. thanks.
Posted by gt on Jul 20, 2007 at 11:50 PM
I like it, because of possiblity to work with associative arrays - it's really powerful!
Posted by Snowcore on Jul 1, 2008 at 11:30 AM