Web Development with jQuery®

(Elliott) #1

(^146) ❘ CHAPTER 5 ITERATION OF ARRAYS AND OBJECTS


Filtering a Selection with a Callback Function


Like each(), the filter() method can be used with a callback function. When it is used in this way,
filter() is similar to each(), in that it allows a callback function to be specifi ed that is subsequently
executed once for every item present in a selection.

With the each() method, you learned that returning a boolean value simulates continue and break
statements. With the filter() method, returning a boolean value decides whether an item should
be kept or removed from the selection. Returning true keeps the item in the selection, and returning
false removes the item from the selection. Using filter() with a callback function is demonstrated
in the following document, Example 5-5:

<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />
<title>Rubber Soul</title>
<script src='../jQuery.js'></script>
<script src='../jQueryUI.js'></script>
<script src='Example 5-5.js'></script>
<link href='Example 5-5.css' rel='stylesheet' />
</head>
<body>
<h4>Rubber Soul</h4>
<ul id='rubberSoul'>
<li class='Paul'>Drive My Car</li>
<li class='John'>Norwegian Wood (This Bird Has Flown)</li>
<li class='Paul'>You Won't See Me</li>
<li class='John'>Nowhere Man</li>
<li class='George'>Think for Yourself</li>
<li class='John'>The Word</li>
<li class='Paul'>Michelle</li>
<li class='John'>What Goes On</li>
<li class='John'>Girl</li>
<li class='Paul'>I'm Looking Through You</li>
<li class='John'>In My Life</li>
<li class='John'>Wait</li>
<li class='George'>If I Needed Someone</li>
<li class='John'>Run for Your Life</li>
</ul>
</body>
</html>

The preceding markup document links to the following style sheet:


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 ;

http://www.it-ebooks.info

Free download pdf