02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

242<br />

CHAPTER 7 ■ ENHANCING THE USER INTERFACE WITH JQUERY<br />

/.*?\?(.*)$/<br />

Regular expressions in JavaScript are delimited <strong>by</strong> forward slashes (/) at each end of the expression.<br />

Inside this expression, the pattern looks for zero or more of any character (from left to right) until the<br />

first time it reaches a question mark; it then stores all characters after the question mark until the end of<br />

the string as a named group for use in the replacement.<br />

■ Note You’ll learn much more about regular expressions <strong>and</strong> how they work in Chapter 9.<br />

Incorporating a Regular Expression into a Script<br />

You want to extract the href value of the link that was clicked, so you’ll use the this keyword. In order to<br />

use <strong>jQuery</strong> methods, you have to pass this as the selector to the <strong>jQuery</strong> function first. Now access the<br />

href value with the .attr() method, then call .replace() <strong>and</strong> extract the query string.<br />

When using regular expressions in .replace(), no quotes are used to enclose the pattern. Using the<br />

regular expression just described, modify init.js to store the query string from the clicked link in a<br />

variable called data; do this <strong>by</strong> adding the code shown in bold:<br />

// Makes sure the document is ready before executing scripts<br />

<strong>jQuery</strong>(function($){<br />

// Pulls up events in a modal window<br />

$("li>a").live("click", function(event){<br />

// Stops the link from loading view.php<br />

event.preventDefault();<br />

// Adds an "active" class to the link<br />

$(this).addClass("active");<br />

// Gets the query string from the link href<br />

var data = $(this)<br />

.attr("href")<br />

.replace(/.+?\?(.*)$/, "$1");<br />

// Logs the query string<br />

console.log( data );

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!