Web Development with jQuery®

(Elliott) #1

Mapping a Selection or an Array (^) ❘ 155
width: 350px;
}
ul li {
padding: 3px;
}
h4 {
margin: 10px 0 ;
}
The following script demonstrates how jQuery’s map() method is used with an array instead of a
selection:
$(document).ready(
function()
{
var songs = [
'Taxman',
'Eleanor Rigby',
'I\'m Only Sleeping',
'Love You To',
'Here, There and Everywhere',
'Yellow Submarine',
'She Said, She Said',
'Good Day Sunshine',
'And Your Bird Can Sing',
'For No One',
'Doctor Robert',
'I Want to Tell You',
'Got to Get You into My Life',
'Tomorrow Never Knows'
];
var mappedSongs = $(songs).map(
function(key)
{
var track = key + 1;
return (track < 10? '0' + track : track) + ' ' + this;
}
);
$(mappedSongs).each(
function()
{
$('ul#revolver').append('

  • ' + this + '
  • ');
    }
    );
    }
    );
    In the preceding script, a collection of song titles of the Beatles’ album Revolver is placed in an
    array and assigned to the variable songs.
    The songs variable is then passed to a call to the dollar sign method, and the map() method is called.
    http://www.it-ebooks.info

    Free download pdf