Web Development with jQuery®

(Elliott) #1

(^142) ❘ CHAPTER 5 ITERATION OF ARRAYS AND OBJECTS
The following style sheet is applied to the preceding markup document:
body {
font: 12px "Lucida Grande", Arial, sans-serif;
color: rgb(50, 50, 50);
margin: 0 ;
padding: 0 10px;
}
ul {
list-style: none;
margin: 0 0 10px 0 ;
padding: 10px;
background: yellow;
width: 250px;
}
ul li {
padding: 3px;
}
h4 {
margin: 10px 0 ;
}
li.rubberSoulEven {
background: lightyellow;
}
In the following script, you see that jQuery’s each() method can be chained onto a selection like any
other method, and you can iterate over the items of the selection:
$(document).ready(
function()
{
$('ul#rubberSoul li').each(
function(key)
{
if (key & 1)
{
$(this).addClass('rubberSoulEven');
}
}
);
}
);
Iterating a selection is essentially the same as iterating an array, only this time when you’re working
with the callback function, the this keyword contains an individual element from the selection. If
you want to use jQuery methods within the callback function, you’ll have to wrap the this keyword
with a call to the dollar sign method. In the example, each

  • element is selected, iterated using
    the each() method, and then the even numbered ones are given the class name rubberSoulEven.
    Figure 5-3 shows the preceding example in a browser.
    http://www.it-ebooks.info

  • Free download pdf