1. Trang chủ
  2. » Giáo án - Bài giảng

wiley javascript bible 7th (2010)

2K 489 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề JavaScript Bible Seventh Edition
Tác giả Danny Goodman
Trường học Unknown Institution
Chuyên ngành JavaScript Programming
Thể loại Book
Năm xuất bản 2010
Thành phố Unknown City
Định dạng
Số trang 2.046
Dung lượng 11,39 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

1Chapter 1: JavaScript’s Role in the World Wide Web and Beyond ...3 Chapter 2: Developing a Scripting Strategy ...15 Chapter 3: Selecting and Using Your Tools ...27 Chapter 4: JavaScript

Trang 3

Praise for Javascript Bible

‘‘JavaScript Bible is the definitive resource in JavaScript programming I am never more than three

feet from my copy.’’

— Steve Reich, CEO, PageCoders

‘‘This book is a must-have for any web developer or programmer.’’

— Thoma Lile, President, Kanis Technologies, Inc

‘‘Outstanding book I would recommend this book to anyone interested in learning to developadvanced Web sites Mr Goodman did an excellent job of organizing this book and writing it so thateven a beginning programmer can understand it.’’

— Jason Hensley, Director of Internet Services, NetVoice, Inc

‘‘Goodman is always great at delivering clear and concise technical books!’’

— Dwayne King, Chief Technology Officer, White Horse

‘‘JavaScript Bible is well worth the money spent!’’

— Yen C.Y Leong, IT Director, Moo Mooltimedia, a member of SmartTransact Group

‘‘A must-have book for any internet developer.’’

— Uri Fremder, Senior Consultant, TopTier Software

‘‘I love this book! I use it all the time, and it always delivers It’s the only JavaScript book I use!’’

— Jason Badger, Web Developer

‘‘Whether you are a professional or a beginner, this is a great book to get.’’

— Brant Mutch, Web Application Developer, Wells Fargo Card Services, Inc

‘‘I never thought I’d ever teach programming before reading your book [JavaScript Bible] It’s so

simple to use — the Programming Fundamentals section brought it all back! Thank you for such awonderful book, and for breaking through my programming block!’’

— Susan Sann Mahon, Certified Lotus Instructor, TechNet Training

‘‘Danny Goodman is very good at leading the reader into the subject JavaScript Bible has everything

we could possibly need.’’

— Philip Gurdon

‘‘An excellent book that builds solidly from whatever level the reader is at A book that is both wittyand educational.’’

— Dave Vane

‘‘I continue to use the book on a daily basis and would be lost without it.’’

— Mike Warner, Founder, Oak Place Productions

‘‘JavaScript Bible is by far the best JavaScript resource I’ve ever seen (and I’ve seen quite a few).’’

— Robert J Mirro, Independent Consultant, RJM Consulting

Trang 5

JavaScript  Bible

Seventh Edition

Trang 7

JavaScript  Bible

Seventh Edition

Danny Goodman Michael Morrison Paul Novitski Tia Gustaff Rayl

Wiley Publishing, Inc.

Trang 8

JavaScript Bible, Seventh Edition

Copyright 2010 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher,

or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should

be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201)748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warrantieswith respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties,including without limitation warranties of fitness for a particular purpose No warranty may be created or extended

by sales or promotional materials The advice and strategies contained herein may not be suitable for every situation.This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or otherprofessional services If professional assistance is required, the services of a competent professional person should besought Neither the publisher nor the author shall be liable for damages arising herefrom The fact that an organiza-tion or web site is referred to in this work as a citation and/or a potential source of further information does not meanthat the author or the publisher endorses the information the organization or web site may provide or recommenda-tions it may make Further, readers should be aware that Internet web sites listed in this work may have changed ordisappeared between when this work was written and when it is read

For general information on our other products and services please contact our Customer Care Department within theUnited States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002

Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be able in electronic books

avail-Library of Congress Control Number: 2010923547

Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc and/orits affiliates, in the United States and other countries, and may not be used without written permission JavaScript is

a registered trademark of Oracle America, Inc All other trademarks are the property of their respective owners WileyPublishing, Inc is not associated with any product or vendor mentioned in this book

Trang 9

cozy Klemperer rosette.

— Paul Novitski

To my husband, Edward, whose love, support, and encouragement kept me going through this and all my adventures, and to the memory of my parents who inspired

me to step out in faith.

— Tia Gustaff Rayl

Trang 11

Danny Goodman is the author of numerous critically acclaimed and best-selling books, including The

Complete HyperCard Handbook, Danny Goodman’s AppleScript Handbook, Dynamic HTML: The Definitive Reference, and JavaScript & DHTML Cookbook He is a renowned authority on and expert teacher of

computer scripting languages His writing style and pedagogy continue to earn praise from readersand teachers around the world

Michael Morrison is a writer, developer, toy inventor, and author of a variety of books coveringtopics such as Java, C++, Web scripting, XML, game development, and mobile devices Some of

Michael’s notable writing projects include Faster Smarter HTML and XML, Teach Yourself HTML

& CSS in 24 Hours, and Beginning Game Programming Michael is also the founder of Stalefish

Labs (www.stalefishlabs.com), an entertainment company specializing in unusual games, toys, andinteractive products

Paul Novitski has been writing software as a freelance programmer since 1981 He once taughthimself BASIC in order to write a machine language disassembler so that he could lovingly hackWang’s OIS microcode He has focused on internet programming since the late ’90s His company,Juniper Webcraft, produces HTML-strict websites featuring accessible, semantic markup, separation

of development layers, and intuitive user interfaces He knows the righteousness of elegant code, thepoignancy of living on the bleeding edge of wilderness, the sweet melancholy of mbira music, and thescorching joy of raising twin boys

Tia Gustaff Rayl is a consultant who does development and training in database and Webtechnologies Most recently she has published courseware for XHTML, CSS, JavaScript, and SQL

It comes as no surprise to those who know her that she began her software career with degrees inEnglish and Education from the University of Florida As is usual for most newcomers to the field,her introduction to computing was maintaining software She went on to a long-standing career

in the software industry in full life cycle system, application, and database development; projectmanagement; and training for PC and mainframe environments In the mid-nineties she worked onearly Web-enabled database applications, adding JavaScript to her repertoire She continues to take ondevelopment projects to maintain her code-slinging skills If she had any spare time (and money) shewould go on an around-the-world cruise with her husband and two dogs

About the Technical Editor

Benjamin Schupak holds a master’s degree in computer science and has more than 11 years of fessional programming experience for large corporations and U.S federal departments He lives in theNew York metro area and enjoys traveling

Trang 15

Hall, my partner in crime at Juniper Webcraft, and, above all, my sweet, loving, supportive,and nearly homicidal spouse Tanya Wright, all of them long-suffering and all to be commendedfor not actually throttling me in the course of this overlong birthing The solid foundation ofresearch and explication established by Danny Goodman and his past collaborators in previouseditions is awesome and I am humbled to have been able to help move this great body of knowledgeforward to the next step Tia Gustaff Rayl, who with wings spread and sparks flying rode in to therescue, has been a kick in the pants to work with; she’s smart and funny, but more than that she isgifted with the precise serendipity and good taste to share a birthday with me.

–Paul Novitski

I have been blessed with the support of many people who have reviewed my work and encouraged

me along the way I could never have done any of this without the devoted support of my husband,Edward I love him without cease and thank God for bringing him into my life I have been blessed bythe remarkable patience of an incredibly tolerant immediate and extended family, as well as amusedfriends, who put up with my ‘‘Hi, I love you Don’t talk to me right now.’’ way of answering the phoneand greeting visitors at the door My husband, family and friends are the ones who sacrificed the mostfor this book Thank you all I want to thank Paul for being great to work with and for his wry sense

of humor which left me on the floor laughing just when I most needed a lift I want to thank my tor, John Sleeva, who with great patience and humor guided me through the maze of the publishingworld I also want to thank Rebecca Anderson and Maraya Cornell for forcing me to be a better writer.Finally, I want to thank Miss Bigelow, my 11th and 12th grade English teacher, who instilled within

edi-me a great respect and love for the written word

–Tia Gustaff Rayl

Trang 17

Part I: Getting Started with JavaScript 1

Chapter 1: JavaScript’s Role in the World Wide Web and Beyond 3

Chapter 2: Developing a Scripting Strategy 15

Chapter 3: Selecting and Using Your Tools 27

Chapter 4: JavaScript Essentials 37

Part II: JavaScript Tutorial 59

Chapter 5: Your First JavaScript Script 61

Chapter 6: Browser and Document Objects 77

Chapter 7: Scripts and HTML Documents 95

Chapter 8: Programming Fundamentals, Part I 109

Chapter 9: Programming Fundamentals, Part II 121

Chapter 10: Window and Document Objects 135

Chapter 11: Forms and Form Elements 153

Chapter 12: Strings, Math, and Dates 179

Chapter 13: Scripting Frames and Multiple Windows 191

Chapter 14: Images and Dynamic HTML 207

Part III: JavaScript Core Language Reference 223

Chapter 15: The String Object 225

Chapter 16: The Math, Number, and Boolean Objects 269

Chapter 17: The Date Object 285

Chapter 18: The Array Object 311

Chapter 19: JSON — Native JavaScript Object Notation 357

Chapter 20: E4X — Native XML Processing 363

Chapter 21: Control Structures and Exception Handling 373

Chapter 22: JavaScript Operators 411

Chapter 23: Function Objects and Custom Objects 437

Chapter 24: Global Functions and Statements 481

Part IV: Document Objects Reference 501

Chapter 25: Document Object Model Essentials 503

Chapter 26: Generic HTML Element Objects 537

Chapter 27: Window and Frame Objects 739

Chapter 28: Location and History Objects 881

Chapter 29: Document and Body Objects 907

Chapter 30: Link and Anchor Objects 995

Chapter 31: Image, Area, Map, and Canvas Objects 1003

Chapter 32: Event Objects 1043

Trang 18

Contents at a Glance

Part V: Appendixes 1123

Chapter A: JavaScript and Browser Objects Quick Reference 1125

Chapter B: What’s on the CD-ROM 1133

Index 1137

Bonus Chapters on the CD-ROM

Part VI: Document Objects Reference (continued) BC1

Chapter 33: Body Text Objects BC2 Chapter 34: The Form and Related Objects BC103 Chapter 35: Button Objects BC128 Chapter 36: Text-Related Form Objects BC153 Chapter 37: Select, Option, and FileUpload Objects BC177 Chapter 38: Style Sheet and Style Objects BC207 Chapter 39: Ajax, E4X, and XML BC272 Chapter 40: HTML Directive Objects BC289 Chapter 41: Table and List Objects BC303 Chapter 42: The Navigator and Other Environment Objects BC360 Chapter 43: Positioned Objects BC411 Chapter 44: Embedded Objects BC448 Chapter 45: The Regular Expression and RegExp Objects BC465

Part VII: More JavaScript Programming BC491

Chapter 46: Data-Entry Validation BC492 Chapter 47: Scripting Java Applets and Plug-Ins BC524 Chapter 48: Debugging Scripts BC564 Chapter 49: Security and Netscape Signed Scripts BC590 Chapter 50: Cross-Browser Dynamic HTML Issues BC608 Chapter 51: Internet Explorer Behaviors BC623

Part VIII: Applications BC636

Chapter 52: Application: Tables and Calendars BC637 Chapter 53: Application: A Lookup Table BC652 Chapter 54: Application: A Poor Man’s Order Form BC665 Chapter 55: Application: Outline-Style Table of Contents BC674 Chapter 56: Application: Calculations and Graphics BC695 Chapter 57: Application: Intelligent ‘‘Updated’’ Flags BC705 Chapter 58: Application: Decision Helper BC715 Chapter 59: Application: Cross-Browser DHTML Map Puzzle BC747 Chapter 60: Application: Transforming XML Data BC764 Chapter 61: Application: Creating Custom Google Maps BC782

Part IX: Appendixes (continued) BC799

Appendix C: JavaScript Reserved Words BC800 Appendix D: Answers to Tutorial Exercises BC801 Appendix E: JavaScript and DOM Internet Resources BC818

xvi

Trang 19

Part I: Getting Started with JavaScript 1

Chapter 1: JavaScript’s Role in the World Wide Web and Beyond 3

Competing for Web Traffic 4

Other Web Technologies 4

JavaScript: A Language for All 10

JavaScript: The Right Tool for the Right Job 12

Chapter 2: Developing a Scripting Strategy 15

Browser Leapfrog 15

Duck and Cover 16

Compatibility Issues Today 17

Developing a Scripting Strategy 22

Chapter 3: Selecting and Using Your Tools 27

The Software Tools 27

Setting Up Your Authoring Environment 28

Validate, Validate, Validate 31

Creating Your First Script 31

Chapter 4: JavaScript Essentials 37

Combining JavaScript with HTML 37

Designing for Compatibility 51

Language Essentials for Experienced Programmers 54

Part II: JavaScript Tutorial 59 Chapter 5: Your First JavaScript Script 61

What Your First Script Will Do 61

Entering Your First Script 62

Have Some Fun 74

Exercises 75

Chapter 6: Browser and Document Objects 77

Scripts Run the Show 77

When to Use JavaScript 78

The Document Object Model 79

When a Document Loads 82

Trang 20

Object References 85

Node Terminology 87

What Defines an Object? 88

Exercises 93

Chapter 7: Scripts and HTML Documents 95

Connecting Scripts to Documents 95

JavaScript Statements 99

When Script Statements Execute 100

Viewing Script Errors 104

Scripting versus Programming 105

Exercises 106

Chapter 8: Programming Fundamentals, Part I 109

What Language Is This? 109

Working with Information 109

Variables 110

Expressions and Evaluation 112

Data Type Conversions 115

Operators 116

Exercises 118

Chapter 9: Programming Fundamentals, Part II 121

Decisions and Loops 121

Control Structures 122

Repeat Loops 124

Functions 124

Curly Braces 128

Arrays 129

Exercises 133

Chapter 10: Window and Document Objects 135

Top-Level Objects 135

The window Object 135

window Properties and Methods 139

The location Object 142

The navigator Object 143

The document Object 143

Exercises 152

Chapter 11: Forms and Form Elements 153

The Form object 153

Form Controls as Objects 158

Passing Elements to Functions with this 170

Submitting and Prevalidating Forms 173

Exercises 177

Chapter 12: Strings, Math, and Dates 179

Core Language Objects 179

String Objects 180

The Math Object 183

The Date Object 184

xviii

Trang 21

Date Calculations 186

Exercises 189

Chapter 13: Scripting Frames and Multiple Windows 191

Frames: Parents and Children 191

References Among Family Members 194

Frame-Scripting Tips 195

About iframe Elements 196

Highlighting Footnotes: A Frameset Scripting Example 196

References for Multiple Windows 202

Exercises 206

Chapter 14: Images and Dynamic HTML 207

The Image Object 207

Rollovers Without Scripts 216

The javascript: Pseudo-URL 219

Popular Dynamic HTML Techniques 220

Exercises 222

Part III: JavaScript Core Language Reference 223 Chapter 15: The String Object 225

String and Number Data Types 225

String Object 228

String Utility Functions 261

URL String Encoding and Decoding 267

Chapter 16: The Math, Number, and Boolean Objects 269

Numbers in JavaScript 269

Math Object 276

Number Object 280

Boolean Object 284

Chapter 17: The Date Object 285

Time Zones and GMT 285

The Date Object 287

Validating Date Entries in Forms 304

Chapter 18: The Array Object 311

Structured Data 311

Creating an Empty Array 312

Populating an Array 313

JavaScript Array Creation Enhancements 314

Deleting Array Entries 315

Parallel Arrays 315

Multidimensional Arrays 320

Simulating a Hash Table 321

Array Object 323

Array Comprehensions 353

Trang 22

Destructuring Assignment 354Compatibility with Older Browsers 355

Chapter 19: JSON — Native JavaScript Object Notation 357

How JSON Works 357Sending and Receiving JSON Data 359JSON Object 360Security Concerns 361

Chapter 20: E4X — Native XML Processing 363

XML 363ECMAScript for XML (E4X) 364

Chapter 21: Control Structures and Exception Handling 373

If and If .Else Decisions 373Conditional Expressions 379The switch Statement 380Repeat (for) Loops 384The while Loop 388The do-while Loop 390Looping through Properties (for-in) 390The with Statement 392Labeled Statements 393Exception Handling 397Using try-catch-finally Constructions 398Throwing Exceptions 402Error Object 407

Chapter 22: JavaScript Operators 411

Operator Categories 411Comparison Operators 412Equality of Disparate Data Types 413Connubial Operators 415Assignment Operators 418Boolean Operators 420Bitwise Operators 424Object Operators 425Miscellaneous Operators 430Operator Precedence 433

Chapter 23: Function Objects and Custom Objects 437

Function Object 437Function Application Notes 447Creating Your Own Objects with Object-Oriented JavaScript 458Object-Oriented Concepts 470Object Object 474

Chapter 24: Global Functions and Statements 481

Functions 482Statements 492WinIE Objects 496

xx

Trang 23

Part IV: Document Objects Reference 501

Chapter 25: Document Object Model Essentials 503

The Object Model Hierarchy 503How Document Objects Are Born 505Object Properties 506Object Methods 507Object Event Handlers 508Object Model Smorgasbord 509Basic Object Model 510Basic Object Model Plus Images 511Navigator 4–Only Extensions 511Internet Explorer 4+ Extensions 512Internet Explorer 5+ Extensions 515The W3C DOM 516Scripting Trends 532Standards Compatibility Modes (DOCTYPE Switching) 534Where to Go from Here 535

Chapter 26: Generic HTML Element Objects 537

Generic Objects 537

Chapter 27: Window and Frame Objects 739

Window Terminology 739Frames 740window Object 746frame Element Object 854frameset Element Object 862iframe Element Object 868popup Object 875

Chapter 28: Location and History Objects 881

location Object 881history Object 900

Chapter 29: Document and Body Objects 907

document Object 908body Element Object 981TreeWalker Object 990

Chapter 30: Link and Anchor Objects 995

Anchor, Link, and a Element Objects 995

Chapter 31: Image, Area, Map, and Canvas Objects 1003

Image and img Element Objects 1003area Element Object 1024map Element Object 1028canvas Element Object 1032

Trang 24

Chapter 32: Event Objects 1043

Why ‘‘Events’’? 1044Event Propagation 1045Referencing the event Object 1059Binding Events 1059event Object Compatibility 1064Dueling Event Models 1066Event Types 1070NN6+/Moz event Object 1097

Appendix A: JavaScript and Browser Objects Quick Reference 1125 Appendix B: What’s on the CD-ROM 1133 Index 1137

Bonus Chapters on the CD-ROM

Part VI: Document Objects Reference (continued) BC1

Chapter 33: Body Text Objects BC2 Chapter 34: The Form and Related Objects BC103 Chapter 35: Button Objects BC128 Chapter 36: Text-Related Form Objects BC153 Chapter 37: Select, Option, and FileUpload Objects BC177 Chapter 38: Style Sheet and Style Objects BC207 Chapter 39: Ajax, E4X, and XML BC272 Chapter 40: HTML Directive Objects BC289 Chapter 41: Table and List Objects BC303 Chapter 42: The Navigator and Other Environment Objects BC360 Chapter 43: Positioned Objects BC411

xxii

Trang 25

Chapter 44: Embedded Objects BC448 Chapter 45: The Regular Expression and RegExp Objects BC465

Part VII: More JavaScript Programming BC491

Chapter 46: Data-Entry Validation BC492 Chapter 47: Scripting Java Applets and Plug-Ins BC524 Chapter 48: Debugging Scripts BC564 Chapter 49: Security and Netscape Signed Scripts BC590 Chapter 50: Cross-Browser Dynamic HTML Issues BC608 Chapter 51: Internet Explorer Behaviors BC623

Part VIII: Applications BC636

Chapter 52: Application: Tables and Calendars BC637 Chapter 53: Application: A Lookup Table BC652 Chapter 54: Application: A Poor Man’s Order Form BC665 Chapter 55: Application: Outline-Style Table of Contents BC674 Chapter 56: Application: Calculations and Graphics BC695 Chapter 57: Application: Intelligent ‘‘Updated’’ Flags BC705 Chapter 58: Application: Decision Helper BC715 Chapter 59: Application: Cross-Browser DHTML Map Puzzle BC747 Chapter 60: Application: Transforming XML Data BC764 Chapter 61: Application: Creating Custom Google Maps BC782

Part IX: Appendixes (continued) BC799

Appendix C: JavaScript Reserved Words BC800 Appendix D: Answers to Tutorial Exercises BC801 Appendix E: JavaScript and DOM Internet Resources BC818

Trang 27

Tover fifteen years of daily work in JavaScript and a constant monitoring of newsgroups for

questions, problems, and challenges facing scripters at all levels Our goal is to help you avoidthe same frustration and head-scratching we and others have experienced through multiple genera-tions of scriptable browsers

While the earliest editions of this book focused on the then-predominant Netscape Navigator browser,the browser market share landscape has changed through the years For many years, Microsoft took astrong lead with its Internet Explorer, but more recently, other browsers that support industry stan-dards are finding homes on users’ computers The situation still leaves an age-old dilemma for contentdevelopers: designing scripted content that functions equally well in both standards-compliant andproprietary environments The job of a book claiming to be the ‘‘bible’’ is not only to present boththe standard and proprietary details when they diverge, but also to show you how to write scriptsthat blend the two so that they work on the wide array of browsers visiting your sites or web applica-tions Empowering you to design and write good scripts is our passion, regardless of browser It’s truethat our bias is toward industry standards, but not to the exclusion of proprietary features that may

be necessary to get your content and scripting ideas flowing equally well on today’s and tomorrow’sbrowsers

Organization and Features of This Edition

Like the previous three editions of the JavaScript Bible, this seventh edition contains far more

infor-mation than can be printed and bound into a single volume The complete contents can be found inthe electronic version of this book (in PDF form) on the CD-ROM that accompanies the book Thisedition is structured in such a way as to supply the most commonly needed information in its entirety

in the printed portion of the book Content that you use to learn the fundamentals of JavaScript andreference frequently are at your fingertips in the printed version, while chapters with more advancedcontent are in the searchable electronic version on the CD-ROM Here are some details about thebook’s structure

Part I: Getting Started with JavaScript

Part I of the book begins with a chapter that shows how JavaScript compares with Java and discussesits role within the rest of the World Wide Web The web browser and scripting world haveundergone significant changes since JavaScript first arrived on the scene That’s why Chapter 2 isdevoted to addressing challenges facing scripters who must develop applications for both single- andcross-platform browser audiences amid rapidly changing standards efforts Chapter 3 introduces sometools you can use to compose your pages and scripts, while Chapter 4 delves into the nitty-gritty ofhow to use JavaScript to run in a wide variety of browsers

Trang 28

Part II: JavaScript Tutorial

All of Part II is handed over to a tutorial for newcomers to JavaScript Ten lessons provide you with

a gradual path through browser internals, basic programming skills, and genuine browser scripting,with an emphasis on industry standards as supported by most of the scriptable browsers in use today.Exercises follow at the end of each lesson to help reinforce what you just learned and challenge you touse your new knowledge (you’ll find answers to the exercises in Appendix D, on the CD-ROM) Thegoal of the tutorial is to equip you with sufficient experience to start scripting simple pages right awaywhile making it easier for you to understand the in-depth discussions and examples in the rest of thebook

Part III: JavaScript Core Language Reference

Reference information for the core JavaScript language fills Part III In all reference chapters, a ibility chart indicates the browser version that supports each object and object feature Guide wordsnear the tops of pages help you find a particular term quickly

compat-Part IV: Document Objects Reference

Part IV, the largest section of the book, provides in-depth coverage of the document object models asimplemented in today’s browsers, including the object used for modern Ajax applications As with thecore JavaScript reference chapters of Part III, these DOM chapters display browser compatibility chartsfor every object and object feature One chapter in particular, Chapter 26, contains reference materialthat is shared by most of the remaining chapters of Part IV To help you refer back to Chapter 26from other chapters, a shaded tab along the outside edge of the page shows you at a glance wherethe chapter is located Additional navigation aids include guide words near the tops of most pages toindicate which object and object feature is covered on the page Note that the Objects Reference begun

in Part IV of the book continues in Part VI on the CD, with an additional 13 chapters of referencematerial

Part V: Appendixes

Appendix A offers a JavaScript and Browser Objects Quick Reference Appendix B provides tion about using the CD-ROM that comes with this book, which includes numerous bonus chaptersand examples

informa-Part VI: Document Objects Reference (continued)

Beginning the portion of the book that resides only the accompanying CD, Part VI continues the ument objects reference discussions that begin in Part IV by providing an additional 13 chapters ofreference material

doc-Part VII: More JavaScript Programming

Chapters 46–51 discuss advanced JavaScript programming techniques, including data-entry validation,debugging, and security issues

Part VIII: Applications

The final ten chapters of the book, available only on the CD-ROM, feature sample applications thatcover the gamut from calendars to puzzles

xxvi

Trang 29

Part IX: Appendixes (continued)

The final three appendixes provide helpful reference information These resources include a list ofJavaScript reserved words in Appendix C, answers to Part II’s tutorial exercises in Appendix D, andInternet resources in Appendix E

CD-ROM

The CD-ROM is a gold mine of information It begins with a PDF version of the entire contents of this

seventh edition of the JavaScript Bible This version includes bonus chapters covering:

 Dynamic HTML, data validation, plug-ins, and security

 Techniques for developing and debugging professional web-based applications

 Ten full-fledged JavaScript real-world applications

Another treasure trove on the CD-ROM is theListings folder where you’ll find over 300ready-to-run HTML documents that serve as examples of most of the document object model andJavaScript vocabulary words in Parts III and IV All of the bonus chapter example listings are alsoincluded You can run these examples with your JavaScript-enabled browser, but be sure to use theindex.htmlpage in the Listings folder as a gateway to running the listings We could have providedyou with humorous little sample code fragments out of context, but we think that seeing full-fledgedHTML documents (simple though they may be) for employing these concepts is important Weencourage you to manually type the script listings from the tutorial (Part II) of this book We believeyou learn a lot, even by aping listings from the book, as you get used to the rhythms of typing scripts

in documents

Be sure to check out the Chapter 4 listing file calledevaluator.html Many segments of Parts IIIand IV invite you to try out an object model or language feature with the help of an interactive work-

bench, called The Evaluator — a JavaScript Bible exclusive! You see instant results and will quickly

learn how the feature works

The Quick Reference from Appendix A is in PDF format on the CD-ROM for you to print out andassemble as a handy reference, if desired Adobe Reader is also included on the CD-ROM, in case youdon’t already have it

Prerequisites to Learning JavaScript

Although this book doesn’t demand that you have a great deal of programming experience behindyou, the more web pages you’ve created with HTML, the easier you will find it to understand howJavaScript interacts with the familiar elements you normally place in your pages Occasionally, you willneed to modify HTML tags to take advantage of scripting If you are familiar with those tags already,the JavaScript enhancements will be simple to digest

To learn JavaScript, you won’t need to know server scripting or how to pass information from a form

to a server The focus here is on client-side scripting, which operates independently of the server afterthe JavaScript-enhanced HTML page is fully loaded into the browser However, we strongly believethat a public web page should be operational in the absence of JavaScript, so any dynamic function-ality that looks up results or modifies the content of a page should interact with a server-side scriptfundamentally After that foundation is laid, we add JavaScript to make a page faster, easier, or more

Trang 30

fun So although you don’t need to know server-side scripting in order to learn JavaScript, for ous web work you should either learn a server-side scripting language such as PHP in addition toJavaScript or look for server-side programmers to complement your client-side scripting abilities.The basic vocabulary of the current HTML standard should be part of your working knowledge Youshould also be familiar with some of the latest document markup standards, such as XHTML andCascading Style Sheets (CSS) Web searches for these terms will uncover numerous tutorials on thesubjects

seri-If you’ve never programmed before

Don’t be put off by the size of this book JavaScript may not be the easiest language in the world tolearn, but believe us, it’s a far cry from having to learn a full programming language such as Java or C.Unlike developing a full-fledged monolithic application (such as the productivity programs you buy instores), JavaScript lets you experiment by writing small snippets of program code to accomplish bigthings The JavaScript interpreter built into every scriptable browser does a great deal of the technicalwork for you

Programming, at its most basic level, consists of nothing more than writing a series of instructionsfor the computer to follow We humans follow instructions all the time, even if we don’t realize it.Traveling to a friend’s house is a sequence of small instructions: Go three blocks that way; turn lefthere; turn right there Amid these instructions are some decisions that we have to make: If the stop-light is red, then stop; if the light is green, then go; if the light is yellow, then floor it! (Just kidding.)Occasionally, we must repeat some operations several times (kind of like having to go around theblock until a parking space opens up) A computer program not only contains the main sequence ofsteps, but it also anticipates what decisions or repetitions may be needed to accomplish the program’sgoal (such as how to handle the various states of a stoplight or what to do if someone just stole theparking spot you were aiming for)

The initial hurdle of learning to program is becoming comfortable with the way a programming guage wants its words and numbers organized in these instructions Such rules are called syntax, thesame as in a living language Computers aren’t very forgiving if you don’t communicate with them inthe specific language they understand When speaking to another human, you can flub a sentence’ssyntax and still have a good chance that the other person will understand you Not so with computerprogramming languages If the syntax isn’t perfect (or at least within the language’s range of knowl-edge), the computer has the brazenness to tell you that you have made a syntax error

lan-The best thing you can do is just accept the syntax errors you receive as learning experiences Evenexperienced programmers make mistakes Every syntax error you get — and every resolution of thaterror made by rewriting the wayward statement — adds to your knowledge of the language

If you’ve done a little programming before

Programming experience in a procedural language, such as BASIC, may actually be a hindrance ratherthan a help to learning JavaScript Although you may have an appreciation for precision in syntax, theoverall concept of how a program fits into the world is probably radically different from JavaScript’srole Part of this has to do with the typical tasks a script performs (carrying out a very specific task

in response to user action within a web page), but a large part also has to do with the nature ofobject-oriented programming

xxviii

Trang 31

If you’ve programmed in C before

In a typical procedural program, the programmer is responsible for everything that appears on thescreen and everything that happens under the hood When the program first runs, a great deal ofcode is dedicated to setting up the visual environment Perhaps the screen contains several text entryfields or clickable buttons To determine which button a user clicks, the program examines the coordi-nates of the click and compares those coordinates against a list of all button coordinates on the screen.Program execution then branches out to perform the instructions reserved for clicking in that space.Object-oriented programming is almost the inverse of that process A button is considered anobject — something tangible An object has properties, such as its label, size, alignment, and so on

An object may also contain a script At the same time, the system software and browser, workingtogether, can send a message to an object — depending on what the user does — to trigger the script.For example, if a user clicks in a text entry field, the system/browser tells the field that somebody hasclicked there (that is, has set the focus to that field), giving the field the task of deciding what to doabout it That’s where the script comes in The script is connected to the field, and it contains theinstructions that the field carries out after the user activates it Another set of instructions may controlwhat happens when the user types an entry and tabs or clicks out of the field, thereby changing thecontent of the field

Some of the scripts you write may seem to be procedural in construction: They contain a simple list

of instructions that are carried out in order But when dealing with data from form elements, theseinstructions work with the object-based nature of JavaScript The form is an object; each radio button

or text field is an object as well The script then acts on the properties of those objects to get somework done

Making the transition from procedural to object-oriented programming may be the most difficult lenge for you But when the concept clicks — a long, pensive walk might help — so many light bulbswill go on inside your head that you’ll think you might glow in the dark From then on, object orien-tation will seem to be the only sensible way to program

chal-By borrowing syntax from Java (which, in turn, is derived from C and C++), JavaScript shares manysyntactical characteristics with C Programmers familiar with C will feel right at home Operator sym-bols, conditional structures, and repeat loops follow very much in the C tradition You will be lessconcerned about data types in JavaScript than you are in C In JavaScript, a variable is not restricted

to any particular data type

With so much of JavaScript’s syntax familiar to you, you will be able to concentrate on documentobject model concepts, which may be entirely new to you You will still need a good grounding inHTML to put your expertise to work in JavaScript

If you’ve programmed in Java before

Despite the similarity in their names, the two languages share only surface aspects: loop andconditional constructions, C-like ‘‘dot’’ object references, curly braces for grouping statements, severalkeywords, and a few other attributes Variable declarations, however, are quite different, becauseJavaScript is a loosely typed language A variable can contain an integer value in one statement and astring in the next (though we’re not saying that this is good style) What Java refers to as methods,JavaScript calls methods (when associated with a predefined object) or functions (for scripter-definedactions) JavaScript methods and functions may return values of any type without having to state thedata type ahead of time

Trang 32

Perhaps the most important Java concepts to suppress when writing JavaScript are the object-orientednotions of classes, inheritance, instantiation, and message passing These aspects are simply non-issueswhen scripting At the same time, however, JavaScript’s designers knew that you’d have somehard-to-break habits For example, although JavaScript does not require a semicolon at the end

of each statement line, if you type one in your JavaScript source code, the JavaScript interpreterwon’t balk

If you’ve written scripts (or macros) before

Experience with writing scripts in other authoring tools or macros in productivity programs is ful for grasping a number of JavaScript’s concepts Perhaps the most important concept is the idea

help-of combining a handful help-of statements to perform a specific task on some data For example, you canwrite a macro in Microsoft Excel that performs a data transformation on daily figures that come infrom a corporate financial report on another computer The macro is built into the Macro menu, andyou run it by choosing that menu item whenever a new set of figures arrives

Some modern programming environments, such as Visual Basic, resemble scripting environments insome ways They present the programmer with an interface builder, which does most of the work ofdisplaying screen objects with which the user will interact A big part of the programmer’s job is towrite little bits of code that are executed when a user interacts with those objects A great deal of thescripting you will do with JavaScript matches that pattern exactly In fact, those environments resem-ble the scriptable browser environment in another way: They provide a finite set of predefined objectsthat have fixed sets of properties and behaviors This predictability makes learning the entire environ-ment and planning an application easier to accomplish

Formatting and Naming Conventions

The script listings and words in this book are presented in amonospace fontto set them apartfrom the rest of the text Because of restrictions in page width, lines of script listings may, from time

to time, break unnaturally In such cases, the remainder of the script appears in the following line,flush with the left margin of the listing, just as it would appear in a text editor with word wrappingturned on If these line breaks cause you problems when you type a script listing into a documentyourself, we encourage you to access the corresponding listing on the CD-ROM to see how it shouldlook when you type it

As soon as you reach Part III of this book, you won’t likely go for more than a page before readingabout an object model or language feature that requires a specific minimum version of one browser

or another To make it easier to spot in the text when a particular browser and browser version isrequired, most browser references consist of an abbreviation and a version number For example,WinIE5 means Internet Explorer 5 for Windows; NN4 means Netscape Navigator 4 for any operat-ing system; Moz stands for the modern Mozilla browser (from which Firefox, Netscape 6 or later, andCamino are derived); and Safari is Apple’s own browser for Mac OS X If a feature is introduced with

a particular version of browser and is supported in subsequent versions, a plus symbol (+) followsthe number For example, a feature marked WinIE5.5+ indicates that Internet Explorer 5.5 for Win-dows is required at a minimum, but the feature is also available in WinIE8 and probably future WinIEversions If a feature was implemented in the first release of a modern browser, a plus symbol imme-diately follows the browser family name, such as Moz+ for all Mozilla-based browsers Occasionally,

a feature or some highlighted behavior applies to only one browser For example, a feature marked

xxx

Trang 33

NN4 means that it works only in Netscape Navigator 4.x A minus sign (e.g., WinIE-) means that thebrowser does not support the item being discussed.

The format of HTML markup in this edition follows HTML5 coding conventions, but also adheres tomany XHTML standards such as all-lowercase tag and attribute names

occasionally appear in the book to flag importantpoints or suggest where to find more information

Trang 35

JavaScript  Bible

Seventh Edition

Trang 37

Part I

Getting Started with JavaScript

IN THIS PART

Chapter 1

JavaScript’s Role in the World

Wide Web and Beyond

Trang 39

JavaScript’s Role

in the World Wide

Web and Beyond

IN THIS CHAPTERHow JavaScript blends with other web-authoring technologies The history of JavaScript What kinds of jobs you should and should not entrust

to JavaScript

Many of the technologies that make the World Wide Web possible

have far exceeded their original goals Envisioned at the outset as

a medium for publishing static text and image content across a

network, the Web is forever being probed, pushed, and pulled by content

authors By taking for granted so much of the ‘‘dirty work’’ of conveying the

bits between server and client computers, content developers and programmers

dream of exploiting that connection to generate new user experiences and

practical applications It’s not uncommon for a developer community to

take ownership of a technology and mold it to do new and exciting things

But with so many web technologies — especially browser programming

with JavaScript — within reach of everyday folks, we have witnessed an

unprecedented explosion in turning the World Wide Web from a bland

publishing medium into a highly interactive, operating system– agnostic

authoring platform

The JavaScript language, working in tandem with related browser features, is a

web-enhancing technology When employed on the client computer, the

lan-guage can help turn a static page of content into an engaging, interactive, and

intelligent experience Applications can be as subtle as welcoming a site’s visitor

with the greeting ‘‘Good morning!’’ when it is morning in the client computer’s

time zone — even though it is dinnertime where the server is located Or,

appli-cations can be much more obvious, such as delivering the content of a slide show

in a one-page download while JavaScript controls the sequence of hiding,

show-ing, and ‘‘flying slide’’ transitions as we navigate through the presentation

Of course, JavaScript is not the only technology that can give life to drab web

content Therefore, it is important to understand where JavaScript fits within the

array of standards, tools, and other technologies at your disposal The alternative

technologies described in this chapter are HTML, Cascading Style Sheets (CSS),

server programs, and plug-ins In most cases, JavaScript can work side by side

with these other technologies, even though the hype can make them sound like

one-stop shopping places for all your interactive needs (That’s rarely the case.)

Finally, you learn about the origins of JavaScript and what role it plays in today’s

advanced web browsers

Trang 40

Part I: Getting Started with JavaScript

Competing for Web Traffic

Web page publishers revel in logging as many visits to their sites as possible Regardless of the tionable accuracy of web page hit counts, a site consistently logging 10,000 dubious hits per week isclearly far more popular than one with 1,000 dubious hits per week Even if the precise number isunknown, relative popularity is a valuable measure Another useful number is how many links fromoutside pages lead to a site A popular site will have many other sites pointing to it — a key to earn-ing high visibility in web searches

ques-Encouraging people to visit a site frequently is the Holy Grail of web publishing Competition forviewers is enormous Not only is the Web like a 50 million–channel television, but also, the Webcompetes for viewers’ attention with all kinds of computer-generated information That includes any-thing that appears onscreen as interactive multimedia

Users of entertainment programs, multimedia encyclopedias, and other colorful, engaging, andmouse-finger-numbing actions are accustomed to high-quality presentations Frequently, theseprograms sport first-rate graphics, animation, live-action video, and synchronized sound By contrast,the lowest-common-denominator web page has little in the way of razzle-dazzle Even with the help

of Dynamic HTML and style sheets, the layout of pictures and text is highly constrained comparedwith the kinds of desktop publishing documents you see all the time Regardless of the quality ofits content, an unscripted, vanilla HTML document is flat At best, interaction is limited to whatevernavigation the author offers in the way of hypertext links or forms whose filled-in content magicallydisappears into the web site’s server

Other Web Technologies

With so many ways to spice up web sites and pages, you can count on competitors for your site’svisitors to do their darnedest to make their sites more engaging than yours Unless you are the solepurveyor of information that is in high demand, you continually must devise ways to keep your visi-tors coming back and entice new ones If you design for an intranet, your competition is the drive forimproved productivity by colleagues who use the internal web sites for getting their jobs done.These are all excellent reasons why you should care about using one or more web technologies to raiseyour pages above the noise Let’s look at the major technologies you should know about

Figure 1-1 illustrates the components that make up a typical dynamic web site The core is a dialogbetween the server (the web host) and the client (the browser); the client requests data and the serverresponds The simplest model would consist of just the server, a document, and a browser, but inpractice web sites use the other components shown here, and more

The process begins when the browser requests a page from the server The server delivers static HTMLpages directly from its hard drive; dynamic pages are generated on-the-fly by scripts executed in a lan-guage interpreter, such as PHP, but likewise delivered by the server to the client, usually in the form

of HTML markup For example, a server-side database can store the items of a catalog, and a PHPscript can look up those data records and mark them up as HTML when requested by the browser.The downloaded page may contain the addresses of other components: style sheets, JavaScript files,images, and other assets The browser requests each of these, in turn, from the server, combining theminto the final rendering of the page

A JavaScript program is inert — just another hunk of downloaded bits — until it’s received by thebrowser, which validates its syntax and compiles it, ready for execution when called upon by the

4

Ngày đăng: 28/04/2014, 17:07

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN