jQuery has two .each() functions to confuse you. The first one is a generic jQuery.each() used to loop through a list of items. The other is a function you can attach to a list, similar to jQuery('p').each(). I will describe the most common form, the jQuery('p').each() form then the generic loop form.
jQuery('select something').each()
You select something using jQuery. Is there one or many? We will use the example of selecting a paragraph with jQuery('p').
There are ? paragraphs in this page. How do we count the paragraphs? We use jQuery('p').length. Create a space for the paragraph count using <span id="paragraphs">?</span>. Replace the questionmark with the actual count using the following code.
<script type="text/javascript">
jQuery(function() {
jQuery('#paragraphs').empty().append(jQuery('p').length);
});
</script>
You can only guarantee there will be a maximum of one if you use an id. An example would be selecting a paragraph with an id, jQuery('p#example-id'), or just an id, jQuery('#example-id'). An id has to be unique. You get one or none.
When you select by element, jQuery('p'), or class, jQuery('.example-class'), you can end up with zero, one, or many. The simplest way to work through the results is to use .each() and place your processing within .each().
Assume you are testing your code and want a simple alert for each result. You could use the following code to see all the items using class example-class.jQuery('.example-class').each(function() { alert(this).tagName; });
jQuery().each()
Lets look at the generic version of .each(). I do not recommend this version and will show some alternatives.
In the previous section, we displayed an alert for every use of a class. Here is the same activity rewritten to use the generic .each() function.jQuery().each(jQuery('.example-class'), function() { alert(this).tagName; });
Yes, the code looks messy and is hard to read, two reasons to not use this form. So why have the function available?
One use for this form is to process arrays. Suppose your code is given an array named abc. You cannot write abc.each();. You can write jQuery().each(abc);. This is one case where the generic .each() function looks useful.
There are better ways to step through an array. You can use the following for loop.
for(i in abc) { alert(abc[i]); }
for is Javascript instead of jQuery and is excellent for arrays because arrays are Javascript, not jQuery.
Conclusion
The best way to process a jQuery list, jQuery('p'), is using the standard each() function. The best way to process a Javascript array is through a Javascript for statement. The generic jQuery().each() should be avoided.





- Facebook Like
- Log in or register to post comments