Web Development with jQuery®

(Elliott) #1

Mapping a Selection or an Array (^) ❘ 153


}


);


$('ul#rubberSoul').hide();

var ul = $('ul#rubberSoulMapped');
ul.show();

$(mappedSongs).each(
function()
{
ul.append('<li>' + this + '</li>');
}
);
}
);

The preceding script begins by selecting all <li> elements in the document. Then a call to the map()
method is chained onto that selection, and a callback function is provided as the fi rst argument to
the map() method.

The callback function provided to the map() method, as with the other methods you’ve observed in
this chapter, passes each item to its callback function in the this keyword. If you need to reference
it, the index or key or counter (whatever you choose to call it) is accessible in the fi rst argument that
you provide to your callback function. Each item is numbered offset from zero, and that counter is
accessible in that fi rst argument. In the preceding example, the fi rst argument is named key.

Inside the callback function, a few expressions look to see what class name each <li> element has.
If the <li> element has a class name of John, for example, the callback function returns the name of
the song with the HTML <i>John Lennon</i> appended to the end. The callback function attaches
the name of the more prominent writer of each song for each song present, building a new array that
is assigned to the variable mappedSongs.

The fi rst <ul> list with id name rubberSoul is hidden by selecting it and making a call to jQuery’s
hide() method and the <ul> with id name rubberSoulMapped is displayed with a call to show().

The each() method is then used to iterate the contents of the mappedSongs variable, appending each
mapped value to the second <ul> element with the id name rubberSoulMapped. Figure 5-7 shows the
fi nal product.

Mapping an Array


Mapping an array basically employs the same logic that you observed in Example 5-7 with map-
ping a selection—you just use an array instead of a selection. So, you can call jQuery’s map() method
with an array the same way that you called the each() method, by either passing an array to the
dollar sign method or by calling the map() method directly, with an array as its fi rst argument and a
callback function as its second argument. The following document, Example 5-8, shows an example
of the map() method as it is applied to an array:

<!DOCTYPE HTML>
<html lang='en'>
<head>

http://www.it-ebooks.info

Free download pdf