Beginning JavaScript - Paul Wilton - E-Book

Beginning JavaScript E-Book

Paul Wilton

4,8
24,99 €

oder
-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

The perennial bestseller returns with new details for using the latest tools and techniques available with JavaScript JavaScript is the definitive language for making the Web a dynamic, rich, interactive medium. This guide to JavaScript builds on the success of previous editions and introduces you to many new advances in JavaScript development. The reorganization of the chapters helps streamline your learning process while new examples provide you with updated JavaScript programming techniques. You'll get all-new coverage of Ajax for remote scripting, JavaScript frameworks, JavaScript and XML, and the latest features in modern Web browsers. Plus, all the featured code has been updated to ensure compliance with the most recent popular Web browsers. * Introduces you to the latest capabilities of JavaScript, the definitive language for developing dynamic, rich, interactive Web sites * Features new coverage of data types and variables, JavaScript and XML, Ajax for remote scripting, and popular JavaScript frameworks * Offers updated code that ensures compliance with the most popular Web browsers * Includes improved examples on the most up-to-date JavaScript programming techniques Continuing in the superlative tradition of the first three editions, Beginning JavaScript, Fourth Edition, gets you up to speed on all the new advances in JavaScript development.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 1102

Veröffentlichungsjahr: 2011

Bewertungen
4,8 (16 Bewertungen)
13
3
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Cover

Title Page

Copyright

Dedication

About the Authors

About the Authors

Credits

Acknowledgments

Introduction

Whom This Book Is For

What This Book Covers

What You Need to Use This Book

Conventions

Source Code

Errata

p2p.wrox.com

Chapter 1: Introduction to JavaScript and the Web

Introduction to JavaScript

Where Do My Scripts Go?

Your First Simple JavaScript Programs

A Brief Look at Browsers and Compatibility Problems

Summary

Chapter 2: Data Types and Variables

Types of Data in JavaScript

Variables — Storing Data in Memory

Using Data — Calculations and Basic String Manipulation

Data Type Conversion

Arrays

Summary

Exercise Questions

Chapter 3: Decisions, Loops, and Functions

Decision Making — The if and switch Statements

Looping — The for and while Statements

Functions

Summary

Exercise Questions

Chapter 4: Common Mistakes, Debugging, and Error Handling

D’oh! I Can’t Believe I Just Did That: Some Common Mistakes

Error Handling

Debugging

Summary

Exercise Questions

Chapter 5: JavaScript — An Object-Based Language

Object-Based Programming

JavaScript’s Native Object Types

Creating New Types of Objects (Reference Types)

Summary

Exercise Questions

Chapter 6: Programming the Browser

Introduction to the Browser’s Objects

Responding to the User’s Actions with Events

Summary

Exercise Questions

Chapter 7: HTML Forms: Interacting with the User

HTML Forms

Other Form Object Properties and Methods

HTML Elements in Forms

Summary

Exercise Questions

Chapter 8: Windows and Frames

Frames and the window Object

Opening New Windows

Security

Summary

Exercise Questions

Chapter 9: String Manipulation

Additional String Methods

Regular Expressions

The String Object — split(), replace(), search(), and match() Methods

Using the RegExp Object’s Constructor

Summary

Exercise Questions

Chapter 10: Date, Time, and Timers

World Time

Timers in a Web Page

Summary

Exercise Questions

Chapter 11: Storing Information: Cookies

Baking Your First Cookie

Creating a Cookie

Getting a Cookie’s Value

Cookie Limitations

Cookie Security and IE6+

Summary

Exercise Questions

Chapter 12: Dynamic HTML and the W3C Document Object Model

The Web Standards

The Document Object Model

Manipulating the DOM

DOM and Events

Writing Cross-Browser DHTML

JavaScript and XML

Summary

Exercise Questions

Chapter 13: Using ActiveX and Plug-Ins with JavaScript

Checking for and Embedding Plug-ins (Non-IE Browsers)

Checking for and Embedding ActiveX Controls on Internet Explorer

Using Plug-ins and ActiveX Controls

Summary

Exercise Question

Chapter 14: Ajax

What Is Ajax?

Using the XMLHttpRequest Object

Creating a Simple Ajax Module

Validating Form Fields with Ajax

Things to Watch Out For

Summary

Exercise Questions

Chapter 15: JavaScript Frameworks

Picking a Framework to Work With

Getting Started

Digging Deeper Into jQuery

Diving into Prototype

Delving into MooTools

Summary

Exercise Questions

Appendix A: Answers to Exercises

Chapter 2

Chapter 3

Chapter 4

Chapter 5

Chapter 6

Chapter 7

Chapter 8

Chapter 9

Chapter 10

Chapter 11

Chapter 12

Chapter 13

Chapter 14

Chapter 15

Appendix B: JavaScript Core Reference

Browser Reference

Reserved Words

JavaScript Operators

JavaScript Statements

Top-Level Properties and Functions

JavaScript and Jscript Core Objects

Appendix C: W3C DOM Reference

DOM Core Objects

HTML DOM Objects

DOM Event Model and Objects

Miscellaneous Events

Appendix D: Latin-1 Character Set

Index

Advertisement

Beginning JavaScript® Fourth Edition

Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256

www.wiley.com

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

Published simultaneously in Canada

ISBN: 978-0-470-52593-7

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 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 Rosewood Drive, 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 warranties with 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 other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared 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 the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Library of Congress Control Number: 2009933758

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Sun Microsystems Incorporated. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

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

In memory of my mum, June Wilton, who in 2006 lost her brave battle against cancer. She was always very proud of me and my books and showed my books to anyone and everyone she happened to meet however briefly and whether they wanted to see them or not! She’s very much missed. — Paul Wilton

To my family: Starla, Hayden, and Evan (whom we haven’t yet met in person). To my parents: Jerry and Judy. Thank you all for your love and support. — Jeremy McPeak

About the Authors

Paul Wilton started as a Visual Basic applications programmer at the Ministry of Defense in the UK and then found himself pulled into the Net. Having joined an Internet development company, he spent three years helping create Internet solutions. He’s now running his own successful and rapidly growing company developing online holiday property reservation systems.

Jeremy McPeak is a self-taught programmer who began his career by tinkering with web sites in 1998. He is the co-author of Professional Ajax, 2nd Edition (Wiley 2007) and several online articles covering topics such as XSLT, ASP.NET WebForms, and C#. He is currently employed in an energy-based company building in-house conventional and web applications.

Jeremy can be reached through his web site www.wdonline.com.

Credits

Acquisitions Editor

Scott Meyers

Project Editor

Maureen Spears

Technical Editor

David M. Karr

Production Editor

Rebecca Anderson

Copy Editor

C.M. Jones

Editorial Director

Robyn B. Siesky

Editorial Manager

Mary Beth Wakefield

Marketing Manager

David Mayhew

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Barry Pruett

Associate Publisher

Jim Minatel

Project Coordinator, Cover

Lindsay Stanford

Compositor

Craig Johnson, Happenstance Type-O-Rama

Proofreader

Kathryn Duggan

Indexer

J & J Indexing

Cover Image

© Photographer’s Choice/Punchstock

Acknowledgments

First, a big thank you to my partner Beci, who, now that the book’s finished, will get to see me for more than 10 minutes a week.

I’d also like to say a very big thank you to Maureen Spears, who has worked very efficiently on getting this book into print.

Thanks also to Jim Minatel for making this book happen.

Many thanks to everyone who’s supported and encouraged me over my many years of writing books. Your help will always be remembered.

Finally, pats and treats to my German Shepherd Dog, Katie, who does an excellent job of warding off disturbances from door-to-door salespeople.

— Paul Wilton

First and foremost, a huge thank you to my wife for putting up with my late nights.

Just as huge thanks go to the people at Wiley Publishing: Jim Minatel and Scott Meyers for making this happen; Maureen Spears who was absolutely wonderful to work with in getting this book into its final, printed form; and David M. Karr for keeping me honest.

Lastly, thank you Nicholas C. Zakas, author of Professional JavaScript, 2nd Edition (Wiley 2009) and co-author of Professional Ajax, 2nd Edition (Wiley 2007), for getting me into this business.

— Jeremy McPeak

Introduction

JavaScript is a scripting language that enables you to enhance static web applications by providing dynamic, personalized, and interactive content. This improves the experience of visitors to your site and makes it more likely that they will visit again. You must have seen the flashy drop-down menus, moving text, and changing content that are now widespread on web sites — they are enabled through JavaScript. Supported by all the major browsers, JavaScript is the language of choice on the Web. It can even be used outside web applications — to automate administrative tasks, for example.

This book aims to teach you all you need to know to start experimenting with JavaScript: what it is, how it works, and what you can do with it. Starting from the basic syntax, you’ll move on to learn how to create powerful web applications. Don’t worry if you’ve never programmed before — this book will teach you all you need to know, step by step. You’ll find that JavaScript can be a great introduction to the world of programming: with the knowledge and understanding that you’ll gain from this book, you’ll be able to move on to learn newer and more advanced technologies in the world of computing.

Whom This Book Is For

To get the most out of this book, you’ll need to have an understanding of HTML and how to create a static web page. You don’t need to have any programming experience.

This book will also suit you if you have some programming experience already and would like to turn your hand to web programming. You will know a fair amount about computing concepts, but maybe not as much about web technologies.

Alternatively, you may have a design background and know relatively little about the web and computing concepts. For you, JavaScript will be a cheap and relatively easy introduction to the world of programming and web application development.

Whoever you are, we hope that this book lives up to your expectations.

What This Book Covers

You’ll begin by looking at exactly what JavaScript is, and taking your first steps with the underlying language and syntax. You’ll learn all the fundamental programming concepts, including data and data types, and structuring your code to make decisions in your programs or to loop over the same piece of code many times.

Once you’re comfortable with the basics, you’ll move on to one of the key ideas in JavaScript — the object. You’ll learn how to take advantage of the objects that are native to the JavaScript language, such as dates and strings, and find out how these objects enable you to manage complex data and simplify your programs. Next, you’ll see how you can use JavaScript to manipulate objects made available to you in the browser, such as forms, windows, and other controls. Using this knowledge, you can start to create truly professional-looking applications that enable you to interact with the user.

Long pieces of code are very hard to get right every time — even for the experienced programmer — and JavaScript code is no exception. You look at common syntax and logical errors, how you can spot them, and how to use the JavaScript debuggers for Firefox, Internet Explorer, Safari/Chrome, and Opera to aid you with this task. Also, you need to examine how to handle the errors that slip through the net, and ensure that these do not detract from the experience of the end user of your application.

From here, you’ll move on to more advanced topics, such as using cookies and jazzing up your web pages with dynamic HTML and XML. Finally, you’ll be looking at a relatively new and exciting technology: Ajax. This allows your JavaScript in a HTML page to communicate directly with a server, and useful for, say, looking up information on a database sitting on your server. If you have the Google toolbar you’ll have seen something like this in action already. When you type a search word in the Google toolbar, it comes up with suggestions, which it gets via the Google search database.

Finally, you’ll explore some of the time saving JavaScript frameworks such as jQuery, Prototype, and MooTools and seeing how they work and how they can help you create sophisticated JavaScript powered applications.

All the new concepts introduced in this book will be illustrated with practical examples, which enable you to experiment with JavaScript and build on the theory that you have just learned.

You’ll find four appendixes at the end of the book. Appendix A provides solutions to the exercises included at the end of most chapters throughout the book. The remaining appendixes contain the reference material that your authors hope you find useful and informational. Appendix B contains the JavaScript language’s core reference. Appendix C contains a complete W3C DOM Core reference — as well as information on the HTML DOM and DOM Level 2 Event model. Appendix D contains the decimal and hexadecimal character codes for the Latin-1 character set.

What You Need to Use This Book

Because JavaScript is a text-based technology, all you really need to create documents containing JavaScript is Notepad (or your equivalent text editor).

Also, in order to try out the code in this book, you will need a web browser that supports a modern version of JavaScript. Ideally, this means Internet Explorer 8 or later and Firefox 3 or later. The book has been extensively tested with these two browsers. However, the code should work in most modern web browsers, although some of the code in later chapters, where you examine dynamic HTML and scripting the DOM, is specific to particular browsers; but the majority of the code presented is cross-browser. Where there are exceptions, they will be clearly noted.

Conventions

To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.

Try It Out

The Try It Out is an exercise you should work through, following the text in the book.

1. It usually consists of a set of steps.

2. Each step has a number.

3. Follow the steps with your copy of the database.

As you work through each Try It Out, the code you’ve typed will be explained in detail.

Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

We highlight in italic type new terms and important words when we introduce them.We show keyboard strokes like this: Ctrl+A.We show file names, URLs, and code within the text like so: persistence.properties. We present code in two different ways:

Important code in code examples is highlighted with a gray background.

The gray highlighting is not used for code that’s less important in the present context, or that has been shown before.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source-code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-52593-7.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

Errata

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time you will be helping us provide even higher-quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

p2p.wrox.com

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system on which you can post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish to provide, and click Submit.

4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

Chapter 1

Introduction to JavaScript and the Web

In this introductory chapter, you look at what JavaScript is, what it can do for you, and what you need in order to use it. With these foundations in place, you will see throughout the rest of the book how JavaScript can help you to create powerful web applications for your web site.

The easiest way to learn something is by actually doing it, so throughout the book you’ll create a number of useful example programs using JavaScript. This process starts in this chapter, by the end of which you will have created your first piece of JavaScript code.

Introduction to JavaScript

In this section you take a brief look at what JavaScript is, where it came from, how it works, and what sorts of useful things you can do with it.

What Is JavaScript?

Having bought this book, you are probably already well aware that JavaScript is some sort of computer language, but what is a computer language? Put simply, a computer language is a series of instructions that tell the computer to do something. That something can be one of a wide variety of things, including displaying text, moving an image, or asking the user for information. Normally, the instructions, or what is termed code, are processed from the top line downward. This simply means that the computer looks at the code you’ve written, works out what action you want taken, and then takes that action. The act of processing the code is called running or executing it.

In natural English, here are instructions, or code, you might write to make a cup of instant coffee:

1. Put coffee crystals in cup.

2. Fill kettle with water.

3. Put kettle on to boil.

4. Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.

5. Drink coffee.

You’d start running this code from the first line (instruction 1), and then continue to the next (instruction 2), then the next, and so on until you came to the end. This is pretty much how most computer languages work, JavaScript included. However, there are occasions when you might change the flow of execution or even skip over some code, but you’ll see more of this in Chapter 3.

JavaScript is an interpreted language rather than a compiled language. What is meant by the terms interpreted and compiled?

Well, to let you in on a secret, your computer doesn’t really understand JavaScript at all. It needs something to interpret the JavaScript code and convert it into something that it understands; hence it is an interpreted language. Computers understand only machine code, which is essentially a string of binary numbers (that is, a string of zeros and ones). As the browser goes through the JavaScript, it passes it to a special program called an interpreter, which converts the JavaScript to the machine code your computer understands. It’s a bit like having a translator translate English to Spanish, for example. The important point to note is that the conversion of the JavaScript happens at the time the code is run; it has to be repeated every time this happens. JavaScript is not the only interpreted language; there are others, including VBScript.

The alternative compiled language is one in which the program code is converted to machine code before it’s actually run, and this conversion has to be done only once. The programmer uses a compiler to convert the code that he wrote to machine code, and this machine code is run by the program’s user. Compiled languages include Visual Basic and C++. Using a real-world analogy, it’s a bit like having a Spanish translator verbally tell you in English what a Spanish document says. Unless you change the document, you can use it without retranslation as much as you like.

Perhaps this is a good point to dispel a widespread myth: JavaScript is not the script version of the Java language. In fact, although they share the same name, that’s virtually all they do share. Particularly good news is that JavaScript is much, much easier to learn and use than Java. In fact, languages like JavaScript are the easiest of all languages to learn, but they are still surprisingly powerful.

JavaScript and the Web

For most of this book you’ll look at JavaScript code that runs inside a web page loaded into a browser. All you need in order to create these web pages is a text editor — for example, Windows Notepad — and a web browser, such as Firefox or Internet Explorer, with which you can view your pages. These browsers come equipped with JavaScript interpreters.

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!