作者:Sbelley Powers 页数:554 出版社:empty |
Why reinvent the wheel everytime you run into a problem withJava Sc ripe?This cook hook is chock-full of code recipes thataddress common programming tasks, as well as techniques forbuilding webapps that work in any browser Just copy and pastethe code samples into your project-youll get the job done fasterand learn more about JavaScript in the process.Youll also leam howto take advantage of the latest features inECMAScript Sand HTML 5, including the new cross-co main widgetcommunication technique, HTML Es video and audio elements,and the drawing canvas, Youll find recipes for using these featureswith JavaScript to build high-quality application interfaces.■Create interactive web and desktop applications■Work with JavaScript objects such as String, Array,mUse JavaScript with Scalable Vector Graphics(SVG) andw Store data in various ways, from the simple to them Program the new HTML 5 audio and video elementsw Implement concurrent programming with Web Workers■Create and use j Query pluginsmUse ARIA and JavaScript to create fully accessible richPrevious experience with basic JavaScript is assumed.USS 49.99CANS 62.99ISBN:978-0-596-80613-29780596806132oks Dnl in-Christopher Schmittauthor CSS CookbookO'REILLY°oreilly.comFree on i need tionfor 45dayawithpurchate ofNumber, and Maththe canvas elementcomplexinternet applications54999
I wrote my fst hook on Java Scrip r 15 years ago, and had to ser am be just to fnd enoughmaterial to fila book.With the JavaScript Cookbook, I had to choose among hundredsof uses to determine what to include.After all these y cars of watching JavaScript grow,lam still surprised at how far-reaching the use of JavaScript has become.In my opinion,there is no more useful programming language or development tool.About the onlytechnology with wider use is HTML.This book is for those who have dabbled with JavaScript and wish to tryout newtechniques, or increase their grasp of both fundamentals and advanced features ofJavaScript.Along the way, I'll demonstrate howto.·Work with the JavaScript objects, such as String, Array, Nu nber, and Math·Create reusable objects·Query and create new elements in the Document Object Model(DOM)·Use the new Selectors API for e ficient and targeted querying·Use JavaScript with new HTML 5 technologies, such as the new media elements,video and audio·Create interactive applications·Manage your webpage space.Store data in various ways, from the simple to the complex·Use JavaScript with Scalable Vector Graphics(SVG) and the canvas element·Work with some of the interesting datastructures, hk e Microformats and RDF a·Pack agc your l brary for others to use, as well as use other libraries in yourapplications·Ensure your JavaScript applications are accessible through the use of Accessible·Work in environments other than the typical desktop browser, such as creatingmobilephone web applications, or extending Photoshop with new behaviors·Debug your applications using your browsers debuggerCommunicate using the new HTML 5 cross-documentation techniques·Implement concurrent programming with Web Workers·Use the File API to access a desktop file directly inch ent-side Java Scrip rIr's not a complete encyclopedia of Java Seri pt use today—no one book can cover allthere is to cover.But hopefully, youll come away with an appreciation of all you canReaders of this ba ok should have some exposure to web development, and the use ofJavaScript.In addition, the recipe format means I'll be focusing on specific tasks, ratherthan providing an overall general introduction.1won't cover every last aspect of aJavaScript topic, such as Strings.Instead, TH focus on the more common tasks, orThere will be lots of code, some of it in code snippets, some in ful-page applicationsThe recipes are also cross-referenced.so if l mention a specific topic in one recipe thatwas covered in another, I'll include this information in the“See Also section for therecipe.To assist you, I've also created example code for all of the recipes that you canThroughout the book, Pll mention the target browsers The majority of example codein this book has been designed for, and tested to work with, the latest releases of thel didn't have a Linux machine to test for that environment, but, knock on wood, mostof the recipes should work in a Linux environment with Firefox.I also didn't have aSystem 7fortestingtheIE9p review.but most of the applications should work, in-Some of the recipes required a specialized environment, such as a mobile device oremulator, or beta(or alpha) release of the browser.I made a note where an exampleRich Internet Applications(ARlA)·Use and create j Query plug-ins·Develop Ajax applications·Work with the new HTML5drag and dropdo with JavaScript.Bonap pett!Audience, Assumptions, and Approachchallenges, associated with the topic.download and work with immediately.Target Browsersmost commonly used browsers:·Firefox 3.6xonMac and Windows·Safari 4.0xonMac and Windows·Opera 10.x on Mac and Windows·Chrome 5.x on Windows·IntemetExplorer8on Windows
Many oi the examples won't work with IE 6.Before I even began the book I decidednot to provide support for lE 6—including any workaround code.Many major sites nolonger support this far too old and too insecure browser, including Amazon, Google,known and sowell-documented onlne, that I felt it was n't necessary to also inch udecoverage in this book.Most of the examples that work with IE 8 will work with IE 7, with some exceptions.1E7doesn't support getAttribute/setAttribute on the common attributes, such asstyle, id, and class, and doesn't support hasAttribute at all.In addition, IE7doesn'tsupport either the CSS selectors, or the Selectors API methods, such as document.query Selector All(covered in Chapter 11) .Where IE7doesn't work, either l provide 1E 7-specific workarounds in comments inthe example code you can download, or I make a note about non support in the recipe—or both.SampleCode ConventionsThere are many code snippets and ful-page examples all through our the hook.Mostare based in HTML, but there are some that are based in XHTML.the XML serializationof HTML.In addition, most of the examples are based in HTML 5, though I've alsoused a couple of other HTML versions, especially with the SVG examples:HTML 5There's only a couple of diference sin the samples based on the HTML version.If theexample is X/HTML 5.you don't need a type attn bute for cit her the style or scriptelements.Additionally.in many of the XHTML sample pages, I surround the code wthThe reason for using aC DATA see ta on for the script block in XHTML i that characterssuch as the angle bracket(<>) and ampersand(Ar) are meaningful in JavaScript, butthey're also meaningful as markup When an XMLparser sees the characters, it wantsto interpret them as markup.To prevent this, the CDATA section tells the par set toI tried to keep all of the style settings and script in the same page to simplify the ex-amples.However, in the real world, you'll want to separate your stylesheet and sc nptinto separate files, as much as possible.Doing so keeps your HTML files clean, andIn the book, I cover basic Java Scrip r functionality t has been around since the dawnof time, and is still essential for application development.I also include recipes coveringsome of the newer functionality, including working with the canvas element, trying outthe new cross-domain widget communication technique(post Ness age) , working withthe new File API and Web Workers, integrating your code with the popular j Querylibrary—even working with the new HTML video and audio elements(which was alotof fun) .l also introduce some of the newer uses of JavaScript, such as in mobile devicesand offline desktop applications, as well as the different fom ms of data storage, andThe book is a relatively esoteric blend of topics, primarily covering those areas whereT've seen both interest and growth in the last few years.l also include an introductionHowever, this book does consist of two rather general sections:the first focuses onexisting Java Scrip r functionality and obj eets; the second focuses more on JavaScriptused within environments, such as a browser.lf you're relatively new to JavaScript,recommend working through all of the recipes in the first 10 chapters before tackling
accessing metadata such as Microformats and RDF a in the webpageOrganizationto the new ECMAScript 5 and HTML 5 innovationsthe recipes later in the bookFollowing is a chapter breakdown of the bookChapter 1, Working with JavaScript StringsChapter 2, Using Regular ExpressionsChapter 3, Dates, Time, and TimersDemonstrates the use of regular expressions, as well as working with the Java Seri ptRegExp object.Recipes include basic how-to s such as swapping words, replacingHTML tags with named entities, validating a Social Security number(and otherpatte med objects) , and globally replacing valuesDesc n be show to access dates and times, as well a show to format date stringstrack elapsed time, find a future date, and using both the new and old ISO 8601Java Scrip r functionality.The chapter also introduces JavaScript timers and work-ing with timers and function closuresChapter 4, Working with Numbers and Mathln cludes basic number functionality, such as keeping an incremental counter andincluding conversions ber ween hexadecimal sand decimals, generating randomcolors, converting strings in tables to numbers, as well as converting between ra-dian and deg tees f important when working with canvas or SVG)Chapter 5, Working with Arrays and LoopsChapter 6, Bulding Reusability with] ava Script FunctionsArrays are the thing in this chapter, which provides a look at howto use arrays tocreate FIFO queues and LIFO stacks, as well a show to sort an array, work withmulti d mensional arrays, traverse arrays, use the new ECMAScript 5arrayfune.tionality to create filtered arrays, and validate array contents The chapter alsocovers associative arrays, as well as various ways to travers c arrays.The Java Scrip r Function is the heart and soul of this language, and this chapterfocuses on howto create functions, pass values to and from the function, create arecursive function, as well as build a dynamic function.The chapter also includeshowto use Memoization and Currying, to enhance application ett i ciency and per-formance, as well a show to use an anonymous function in order to wrap globalvariablesChapter 7, Handling EventsCovers basic event hand lng tasks, including capturing events, canceling events,accessing the Eventobject, as well as working with both mouse and keyboardevents.The chapter a so covers the new HTML5drag and-drop functional y, aswell as working with Safari'sOn entation Events(for mobile development) .Chapter 8, Browser PiecesThis chapter gets into the basic working componen is all browsers, and many otheruser agents, share This includes creating new windows, changing a stylesheet,modifying an image, adding a bread crum h to a webpage, bookmarking a dynamicpage.as well as preserving the back button in Ajax applications.The chapter alsointroduces the new HTML 5 History functionality for preserving dynamic stateChapter 9, Form Elements and Vahdat ionThis chapter continues the introduction of regular expressions from Chapter 2, butfocuses on form elements and val dation.The chapter also cover show teen ableand disable form elements and hide or display elements, and in eludes how iomodify a selection lst, and can ceng a form submissionChapter 10, Debug gig and Error HandlingNone of us like it,allofusneedit:thischapterfocusesonerrorhandnginap-Pe lace|xiplications, as well a show to use the diferent debugging tools in the book'star gerbrowsersChapter 11.Accessing Page ElementsThis chapter covers the various ways you can access one or more documentelements.Included are discussions on accessing all elements of a certain type, aspecific element, or using the newer Selectors API to use CSS-ike syntax to findelements.Also included is a discussion of namespace specifics, where appropriateChapter 12, Creating and Removing Elements and AttributesThe chapter includes ways to create and add elements to a web document, includ-ang adding text, paragraphs, working with i able elements, and moving and remov-in gd acumen t elements, The chapter also cover show to add and access elementattributes, and includes coverage of namespace specifics, where approp ni ateChap rer 13, Working with WebPage SpacesThe webpage is a canvas on which we create, and this chapter cover show toChapter 14, Creating Interactive and Accessible Effects with JavaScript, CSS, and ARIAChapter 15, Creating Me dua Rich and Interactive App icationsdetermine the area of the webpage, the sizeof page clements, their location, aswell a show to hide and show page sections.Popular behaviors such as expand os/accordions and pa gc overlays, as well a stabbed pages are included, as is howtocreate a collapsible sidebar and a hover-based pop-up messageFor the longest tim c, our dynamic webpage efects were liter ll silent to a sign ificant web community those using screen readers.This chapter introduces thenew Web Accessiblity Initiative-Accessible Rich Inte met Applications(WAI-ARIA) attributes and roles and demonstrate show they can make a webpage comealive for all readers, nor just those who are sighted.The chapter also covers othervery common interactive effects, including providing a flash of color to signal anevent, working with pop-up messages, creating Live Regions, and providing ac-cessible eft ects when validating forms.I am not the most artistic of souls, but I do know howto make JavaScript workwith the canvas element and SVG.In this chapter, I provide the basic steps neededin order to work with both of these media, as well as the new erWebGL3Denvi-ronment, and the new HTML 5 video and audio elementsChapter 16, JavaScript ObjectsProbably one of the most important chapters in the book, this chapter covers thebasics of creating Java Scrip i objects, including howto keep data members private,adding Geri ers/Setters, using the new ECMAScript 5 object protection function-ality, chaining object methods, and using the new Prototype.bind.wm|Preface
1.Working with JavaScript Strings........
2.Using Regular Expressions..
3.Dates, Time, and Timers..
4.Working with Numbers and Math...
5.Working with Arrays and Loops..
6.Building Re usa bit y with JavaScript Functions.
w|Table of Cent ents
L 1 Concatenating Two or More Strng s
a New Array
12 Concatenating a String and Another DataType
1.3 Conditionally Comparing Strings
L+Finding a Substring in a String
1.5 Extracting a Substring from a String
1.6 Checking for an Existing, Nonempty String
1.7 Breaking a Keyword String into Separate Keywords
L. 8 Inserting Special Characters
1.9 Processing Individual Lines of a textarea
1.10 Trimming Whitespace from the Ends of a String
1.11 Left-or Right-Pada String
21TestngWheheraSubstnng Exits
2.2 Testing for Case-In sens ive Subst ng Matches
23 Validating a Social Security Number
2.4 Finding and Highlighting Ali Instances of a Pat tem
25ReplacingPattems with New Strings
2.6SwapWordsina String Using Capturing Parentheses
2.7 Using Regular Expressions to Trim Whitespace
2.8 Replace HTML Tags with Named Entities
2.9 Searching for Special Characters
3.1 Printing Out Today's Date
3.2 Printing Out the UTC DateandTime
3.3 Printing Out an ISO 8601 Formatted Date
3.4ConveriganISO 8601 Formatted Date to a Format Acceptable
to the Date Object
3.5 Creating a Specific Date
3.6 Scheduling a Future Date
3.7 Tracking Elapsed Time
3.8Creacinga Timeout
3.9 Creating Recurring Timers
3.10 Using Function Closures with Timers
41 Keeping an Incremental Counter
4.2 Converting a Decimal to a Hexadecimal Value
4.3 Creating aR and on Number Generator
4.4 Randomly Generating Colors
4.5 Converting Strings in a Table to Numbers
4.6 Summing All Numbers in a TableColumn
4.7 Converting Between Degrees and Radians
4.8 Find the Radius and Center of a Circle to Fit Within a Page Element 65
4.9Caleulating the Length of a Cir eula rAre67
5.1 Looping Through an Array
5.2 Creating a Multidimensional Array
5.3 Creating a String from an Array
5.4 Sorting an Array
5.5 Store and Access Values in Order
5.6 Store and Access Values in Reverse Order
5.7CreateaNewArrayasa Subset of an Existing Array
5.8 Searching Through an Array
5.9Flattena Multidimensional Array
5.10 Search and Remove or Replace Array Elements
s.1iAppyingaFuntonAganstEa hAtay Element
5.12 Applying a Function to Every Element in an Array and Returning
5.13 Creating a Filtered Array
5.14Val dating Array Contents86
5.15UsinganAssnciativeA tray to Store Form Element Names and
6.1 Creating a Block of Reusable Code94
6.2 Passing Single Data Values to and from a Function9;
6.3 Passing Complex DataObjects to a Function96
81Ask the WebPage Reader to Con imi an Actin
8.2 Creating a New, Stripped-Down Browser Window
8.3 Finding Out About the Browser Accessing the Page
8.4 Warning the WebPage Reader About Leaving a Page
8.5 Changing Stylesheets Depending on Color Support
8.6 Modifying Image Dimensions Depending on PageSize
8.7CreatingBreaderumbsina CMS Template Page
8.8 Bookmarking a Dynamic Page
8.9 Preserving State for Back Button, Page Refresh
9.1 Accessing Form Text In pur Values
9.2DynarnicallyDisablng and Enabling Form Elements
9.3 Getting Information from a Form Element Based on an Event
9.4 Performing an Action When a RadioButton Is Cl cked
9.5 Checking for a Valid Phone Number
9.6 Canceling a Form Submission
9.7 Preventing Duplicate Form Submissions
9.8 Hiding and Displaying Form Elements
99 Modifying a Selection List Based on Other Form Decisions
10.1 Gracefully Handing No JavaScript Support
10.2 Checking to r Errors in Functions
10.3 Using an Alert for Simple Debugging
10.4 Catching an Error and Providing Graceful Error HandlingIs
10.5 Initiating Manageable Errors
10.6 Using Firebug with Fire to x185
10.7Seutinga Breakpoint and Examining Data with Firebug188
10.8 Firefox and the Console190
10.9UsingIE's Built-in Debugger194
10.10Sertinga Breakpoint with IE Developer Tools196
10.11 Opera's Dragonfly198
10.12 Setting a Breakpoint with Dragonfly201
10.13 Turning on Safari's Development Tools
10.14 Setting a Breakpoint with Safari's Debugger
10.15 Debugging in Chrome
111 Access a Given Element and Find ts Parent and Child El ents214
11.2 Accessing All Images in the WebPage
11.3 Discover All Images Within an Article
11.4 Discover all Images in Articles Using the Selectors API
11.5 Finding the Parent Element for a Group of Elements
11.6 Highlighting the First Paragraph in Every Element
11.7ApplyaStnpingThemetoan Unordered List
11.8 Creating an At ray of All Elements of a Given Class
11.9 Finding All Elements That Share an Attribute
11.10 Finding All Checked Options
11.11 Summing All the Values in a Table Row
11.12Ger Element Attributes
11.13Ger Style Information for an Element238
1.1UsinginnerHTMLAQuck and Easy Approach to Add ng
12.2 Inserting Elements Before Existing Page Elements
12.3 Appending a New Element to the End of a Page
12.4 Triggering Older Version sofIE to Style New Elements
12.5 Inserting a New Paragraph
12.6 Adding Text to a New Paragraph249
12.7 Adding Attributes to an Existing Element251
12.8 Testing for a Boolean Attribute
12.9 Removing an Attribute
12.10 Moving a Paragraph
12.11 Replacing Links with Footnote Bullets
12.12AddingRowstoan Existing Table
12.13 Removing a Paragraph from a div Element
12.14 Deleting Rows from an HTML Table
12.15 Changing the Element'sCSS Style Properties
13.1Determinng the Area of the WebPage
13.2 Measuring Elements
13.3 Locating Elements in the Page
13.4 Hiding Page Sections
135 Creating Collapsible Form Sections
13.6 Adding a Page Overlay
13.7 Creating Tab Pages
13.8 Creating Hover-Based Pop-up Info Windows
13.9 Collapsing or Resizing the Sidebar
14.1 Displaying a Hidden Page Section
14.2 Creating an Alert Message
18.1Accesing the XMLHttpRequest Objec
18.2 Preparing the Data for Transmission
18.3 Determining the Type of Query Call
18.4 Adding a Callback Function to an Ajax Request
18.5 Checking for an Error Condition
18.6 Processing a Text Result
13.Working with WebPage Spaces..
14.Creating Interactive and Accessible Effects with JavaScript CSS, and ARIA...... 297
15.Creating Meda Rich and Interac ve Appli ations....325
16.JavaScript Objects...359
17, JavaScript Libraries..,389
14.3 Highlighting FormField with Missing or In corre er Data
14.+Adding Keyboard Accessibility to a Page Overlay
14.5 Creating Collapsible Form Sections
14.6 Displaying a Flash of Color to Signal an Action
14.7AddingARIA Attributes to a Tabbed Page Application
14.8 Live Region
15.1Creaing Basic Shapes in Canvas(Using the canvas Element)
15.2 Implementing Canvas Applications in IE
15.3 Creating a Dynamic Line Chart in Canvas
15.4 Adding JavaScript to an SVG File
15.5 Accessing SVG from WebPage Scrip c
15.6EmulatingSVGin InternetExplorer
15.7 Enable Interactive SVG Embedded in HTML
15.8 Using the Math Functions to Create a Realistic, Ticking Analog
15.9 Integrating SVG and the Canvas Element in HTML
15.10TurningonWebGL Support in Firefox and WebKit/Sa fan
15.11 Running a Routine When an AudioFile Begins Playing
15.12 Controlling Video from Java Sen pt with the video Element
16.1 Defining a Basic JavaScript Object
16.2 Keeping Object Members Private
16.3 Expanding Objects with prototype
16.4 Adding Getter/Setter to Objects
16.5 Inheriting an Objects Functionality
16.6ExtendinganObjecrby Defining a New Property
16.7 Enumerating an Object's Properties
16.8 Preventing Object Exten sib lity
16.9 Preventing Object Additions and Changes to Property Descriptors
16.10 Preventing Any Changes to an Object380
16.11One-Off Objects and Name spacing Your Java Scrip r381
16.12 Rediscovering“this”with Prototype.bind383
16.13 Chaining Your Object's Methods385
17.1 Packaging Your Code390
17.2 Testing Your Code with Js Unit
17.3Minify Your Library
17.4 Hosting Your L.ibrary一沙
17.5 Using an External Library:Building on the j Query Framework400
176 Using Existing j Query Plug-ins402
17.7 Convert Your Library to aj Query Plug-in404
17.8 Safely Combining Several Libraries in Your App ications408
18.Communication..413
19.Working with Structured Data..,435
x|TableofContents
Clock in SVG
TableofContents|u
18.7MakinganAjax Request to Another Domain(Using JSON P)
18.8 Populating a Selection List from the Server
18.9 Using a Timer to Automatically Update the Page with Fresh Data
18.10 Communicating Across Windows with Post Message
19.1 Process an XML.Document Retu med from anAl a x Call436
19.2 Extracting Pertinent Information from an XML Tree437
19.3GenerateaJavaScnpt Object with JSON, Old-School Style442
19.5ConvertanObjecttoaFikte red/Transformed String with JSON
19.6Converth Calendar Microformat Annotations
19.7GleanPageRDFa and Convert It into JSON Using rdf Query and
20.1Attachng Persistent Information to URLs
20.2 Creating a Cookie to Persist Information Across Pages
20.3 Persisting Information Using the History, push State Method and
20.4 Using session Storage for Client-Side Storage
20.5 Creating a local Storage Client-Side Data Storage Item
20.6 Persisting Data Using a Relational DataStore
21.1Creaiga Browser Add-On, Plug-in, or Extension
21.2CreatingDeskiop and Mobile Widgets
213 Creating JavaScript Applications for the iPhone, Android, and
21.4 Enhancing Tools with Java Scrip r
21.5Creatng Efficient Desktop Applications with
20.Persistence....
21.JavaScript Outside the Box..
Index..