modern-web-design-and-development

(Brent) #1

.each()


each() loops over the elements, but it can be used in two ways. The first
and most common involves passing a callback function as its only
argument, which is also used to act on each element in succession. For
example:


1 $('p').each(function() {

(^2) alert($(this).text());
3 });
This visits every

in our document and alerts out its contents.
But each() is more than just a method for running on selectors: it can also
be used to handle arrays and array-like objects. If you know PHP, think
foreach(). It can do this either as a method or as a core function of
jQuery. For example...
1 var myarray = ['one', 'two'];
2 $.each(myarray, function(key, val) {
(^3) alert('The value at key '+key+' is '+val);
4 });
... is the same as:
1 var myarray = ['one', 'two'];
2 $(myarray).each(function(key, val) {
(^3) alert('The value at key '+key+' is '+val);
4 });
That is, for each element in myarray, in our callback function its key and
value will be available to read via the key and val variables, respectively.
The first of the two examples is the better choice, since it makes little sense
to pass an array as a jQuery selector, even if it works.

Free download pdf