Web Development with jQuery®

(Elliott) #1

(^138) ❘ CHAPTER 5 ITERATION OF ARRAYS AND OBJECTS
In the preceding script, you create a couple of arrays, one for beatles and one for albums. In the fi rst
iteration, the variable beatles is passed to jQuery’s dollar sign method, and then jQuery’s each()
method is chained onto that. You pass a callback function to jQuery’s each() method, which is exe-
cuted once for each item in the array; upon each execution, the current item is passed to the callback
function; the value is assigned to this. You can also defi ne arguments within the callback function
to get the current key (a numeric offset in the case of an array or list) or the current value, like so:
$(beatles).each(
function(key, value)
{
ul.append('

  • ' + value + '
  • ');
    }
    );
    For these two arrays, the numeric offset is provided in key, the fi rst argument, and the value is
    provided in the second argument, value. The same value is assigned to the special contextual
    keyword: this, which is available only within the callback function itself.
    Figure 5-1 shows that both
      elements are populated with new
    • elements via script.


      FIGURE 5-1


      In the preceding example, you see how jQuery can eliminate the traditional for construct that you’d
      typically use for iterating the contents of an array or list. Instead, you pass an array to jQuery’s dol-
      lar sign method so that you have the full power of jQuery at your disposal for use with that array.
      Then you chain a call to jQuery using the each() method, which takes a callback function as its
      only argument. That callback function then is executed once for each item in the array, eliminating
      the need for a counter because the current item is passed to the function with each iteration in the

      http://www.it-ebooks.info

    Free download pdf