Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition) P47 ppsx

10 311 0
Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition) P47 ppsx

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

Thông tin tài liệu

Introducing JavaScript Introducing JavaScript JavaScript was initially introduced with Netscape Navigator 2.0. Before its introduction, there was no way to add interactive content to web pages. If you wanted to create an interactive application, you had to do everything on the server using CGI scripts or other server-side techniques. Netscape embedded a JavaScript interpreter within its browser so that web designers could add programs to their pages to provide interactive content. JavaScript is useful because it's deeply integrated with the browser. This integration allows it to manipulate various aspects of the browser behavior, as well as objects included on an HMTL page. JavaScript uses what's referred to as an event-driven model of execution. When you embed JavaScript code in a web page, it isn't run until the event it's associated with is triggered. The types of events that can call JavaScript include loading the page, leaving the page, interacting with a form element in some way, or clicking a link. Plenty of other events are available as well. Many of these events are taken advantage of in what most users would consider to be annoying ways. For example, many sites open an additional window containing an advertisement when you navigate to one of their pages. This is accomplished using JavaScript and the page load event. Other sites open additional windows when you leave them; this is also accomplished using JavaScript triggered on an event. Less annoying applications include displaying a custom message in the status bar when a user holds the mouse over a link, and swapping out images when the user moves the mouse over them. Why Would You Want to Use JavaScript? JavaScript enables you to manipulate web pages without sending a request back to the server. Using this capability, you can alter elements on a page, validate user input before a user submits a form, and modify the behavior of the browserall by using scripts embedded within your web pages. Let's look at some of the advantages of using JavaScript to enhance your web pages. Ease of Use Unlike Java, JavaScript is designed for nonprogrammers. As such, it's relatively easy to use and is far less pedantic about details such as the declaration of variable types. In addition, you don't need to compile JavaScript code before it can be used, unlike most other languages, including Java. Still, JavaScript is a scripting language, which gives it a steeper learning curve than HTML (although JavaScript's curve isn't as steep as Java's). Without any programming background, however, you can use JavaScript for very simple tasks such as the ones presented later in this lesson. More complex jobs require learning key programming concepts and techniques. Increasing Server Efficiency Some JavaScript applications can save round trips to the server, and prevent the user from waiting for a form submission to be processed. In other cases, you can use advanced JavaScript applications along with programs on the server to update parts of a page rather than reloading the entire thing. I'll discuss that in Lesson 15, "Creating Applications with Dynamic HTML and AJAX." Traffic on the Internet is only going up, and you never know when a website is going to be the next hot thing. Reducing server traffic through the use of JavaScript can help ensure that your website remains responsive even as traffic goes up. Let's say that you've created a form that people use to enter their billing details into your online ordering system. When this form is submitted, your CGI script first needs to validate the information provided and make sure that all the appropriate fields have been filled out correctly. It needs to check that a name and address have been entered, that a billing method has been selected, that credit card details have been completedand the list goes on. file:///G|/1/0672328860/ch12lev1sec1.html (1 von 2) [19.12.2006 13:49:28] Introducing JavaScript But what happens if your CGI script discovers that some information is missing? You need to alert the visitor that there are problems with the submission and then ask the user to edit the details and resubmit the completed form. This process involves sending the form back to the browser, having the visitor resubmit it with the right information, revalidating it, and repeating the process until everything is current. This process is very resource-intensive, both on the server side (each CGI program takes up CPU and memory time) and in the repeated network connections back and forth between the browser and the server. By adding validation and checking procedures to the web browser with JavaScript, you can reduce the number of transactions because many errors will be caught before forms are ever submitted to the server. And, because the web server doesn't need to perform as many validations of its own, fewer server hardware and processor resources are required to process form submissions. The side benefit is that users will find your application more responsive because the trip back to the server isn't required for validation. Integration with the Browser You can add interactive features to your pages using Java applets or plug-ins such as Macromedia Flash and Macromedia Shockwave. However, these technologies are separate from the pages that they're embedded within. JavaScript, on the other hand, enables you to manipulate objects on the page such as links, images, and form elements. You can also use JavaScript to control the browser itself by changing the size of the browser window, moving the browser window around the screen, and activating or deactivating elements of the interface. None of these options is available with Java or plug-ins. file:///G|/1/0672328860/ch12lev1sec1.html (2 von 2) [19.12.2006 13:49:28] The <script> Tag The <script> Tag To accommodate the inclusion of JavaScript programs in a normal HTML document, Netscape introduced the <script> tag. By placing a <script> tag in a document, you tell the web browser to treat any lines of text following the tag as script rather than as content for the web page. This continues until a corresponding </script> tag is encountered, at which point the browser reverts to treating text as web content. When used in a document, every script tag must include a language attribute to declare the scripting language to be used. If you're writing a script in JavaScript, you should use the attribute language="JavaScript". Note JavaScript has now appeared in five versions of Netscape Navigator and two versions of Microsoft Internet Explorer, plus Mozilla Firefox and Opera. This means that there are now several possible values for the language attribute. With Navigator 3, Netscape extended JavaScript to JavaScript 1.1. Netscape Navigator 4.0 added even more to JavaScript and called it JavaScript 1.2. Navigator 4.5 introduced JavaScript 1.3. Even though many browsers have been released since Netscape Navigator 4.5, the version number for JavaScript remains the same. The Structure of a JavaScript Script When you include any JavaScript code in an HTML document (apart from using the <script> tag), you should also follow a few other conventions: ● As a rule, the <script> tag should be placed between the <head> and </head> tags at the start of your document, not between the <body> tags. This isn't a hard-andfast requirement (as you'll learn later), but it's a standard that you should adopt whenever possible. Because the code for your scripts won't be displayed on the web page itself, it should be included in the <head> section with all the other control and information tags, such as <title> and <meta>. ● Unlike HTML, which uses the <! comment tag >, comments inside JavaScript code use the // symbol at the start of a line. Any line of JavaScript code that starts with this symbol will be treated as a comment and ignored. Taking these three points into consideration, the basic structure for including JavaScript code inside an HTML document looks like this: <html> <head> <title>Test script</title> <script language="JavaScript"> // Your JavaScript code goes here </script> </head> <body> Your Web document goes here file:///G|/1/0672328860/ch12lev1sec2.html (1 von 2) [19.12.2006 13:49:29] The <script> Tag </body> </html> The src Attribute Besides the language attribute, the <script> tag can also include an src attribute, which allows a JavaScript script stored in a separate file to be included as part of the current web page. This option is handy if you have several web pages that use the same JavaScript code and you don't want to copy and paste the scripts into each page's code. When used this way, the <script> tag takes the following form: <script language="JavaScript" src="http://www.myserver.com/script.js"> In this form, script can be any relative or absolute URL, and .js is the file extension for a JavaScript file. file:///G|/1/0672328860/ch12lev1sec2.html (2 von 2) [19.12.2006 13:49:29] Basic Commands and Language Structure Basic Commands and Language Structure JavaScript is an object-based language. It accesses the browser and elements on the page in an object- oriented fashion. All the objects are stored in a hierarchy, and you can specify specific elements in the hierarchy using a dot-based notation that I'll explain in a bit. Using this structure, all the elements of a single web page are contained within a base object container called window. Inside the window object is a set of smaller containers (or objects) that hold information about the various elements of a web page. The following are some of the main objects: location Contains information about the location of the current web document, including its URL and separate components such as the protocol, domain name, path, and port. history Holds a record of all the sites that a web browser has visited during the current session, and also gives you access to built-in functions that enable you to change the contents of the current window. document Contains the complete details of the current web page. This information includes all the forms, form elements, images, links, and anchors. It also provides many functions that enable you to programmatically alter the contents of items such as text boxes, radio buttons, and other form elements. You can find a complete list of the available objects in JavaScript in Microsoft's JScript reference at http://msdn.microsoft.com, and in the Mozilla JavaScript documentation at http://developer.mozilla.org/ en/docs/JavaScript. Objects are accessed using a dot-based notation. To refer to a specific object, you need to locate it within the object hierarchy. For example, to refer to a form field called quantity in the first form on a page, you'd refer to it as document.forms[0].quantity. When multiple objects of the same type appear at the same location in a hierarchy, you have to refer to them by position in a list or by name. In this case, I'm referring to the first form on the document, so it's in the first position in the listthus, forms[0]. JavaScript, like most programming languages, starts counting at zero. Properties and Methods Within each object container, you can access two main types of resources: properties and methods. Properties are variables that hold a value associated with the object you're interested in. For example, within the document object is a property called title that contains the title of the current document as described by the <title> tag. In JavaScript, you obtain the value of this property by using the command document.title. Properties are accessed using the dot notation I mentioned earlier. The item after the final dot is the property that you want to reference. Some examples of properties that you can use include the following: file:///G|/1/0672328860/ch12lev1sec3.html (1 von 8) [19.12.2006 13:49:30] Basic Commands and Language Structure document.bgcolor The color of the page's background document.fgcolor The color of the page's text document.lastModified The date the page was last modified document.title The title of the current web page form.action The URL of the CGI script to which the form will be submitted location.hostname The hostname of the current web page's URL See the JavaScript documentation at http://developer.mozilla.org/en/docs/JavaScript for all the properties of each built-in object. Methods are actions associated with a particular object. For example, the document object has a method called write associated with it that enables you to write text directly onto a web page. It takes the following form: document.write("Hello world"); As was the case with properties, you execute, or call, a method by referencing the object that it's associated with, followed by a dot, and then the name of the method itself. Method names are followed by parentheses ( ()). The parentheses surround any arguments to that method. For example, if the method operates on numbers, the parentheses will contain those numbers. In the "Hello World" example, the write() method takes a string to write as an argument. Note that even if a method accepts no arguments, you still have to include the parentheses. For example, the toString() method, which belongs to the location object, is used to convert the current document's URL into a string suitable for use with other methods such as document.write(). This method has no arguments. You just call it with empty parentheses, like this: location.toString(). The parentheses are necessary to distinguish between methods and properties. As with properties, each object has a set of methods that you can use in your JavaScript scripts. The full list is at the same URL as the list of objects and properties mentioned earlier. Here are a few choice methods: document.write(string) Writes HTML or text to the current page. string is the text to write. form.submit() Submits the form. window.alert(string) Pops up an alert box. string is the message to display in the alert. window.open(URL, name) Opens a new browser window. URL is the URL of the page to open, and name is the window name for frame or link targets. By combining the document.write() and location.toString() methods and the document.title property mentioned previously into an HTML document, you can create a simple JavaScript script such as the one shown here: file:///G|/1/0672328860/ch12lev1sec3.html (2 von 8) [19.12.2006 13:49:30] Basic Commands and Language Structure Input <html> <head> <title>Test JavaScript</title> <script language="JavaScript"> <! hide from old browsers document.write(document.title + "<br />"); document.write(location.toString()); // done hiding > </script> </head> </html> The results are shown in Figure 12.1. Output Figure 12.1. The results of your first JavaScript script. [View full size image] Caution Method, property, function, and variable names in JavaScript are all case sensitive. That is, uppercase and lowercase are different. If you're having problems getting the script for Figure 12.1 to work, make sure that you've written location.toString() and not location. tostring() . Events and JavaScript Although implementing methods such as document.write() to create web pages might be useful, the real power behind JavaScript lies in its capability to respond to events. As I mentioned earlier, events are actions that occur on a web page, normally when a visitor interacts file:///G|/1/0672328860/ch12lev1sec3.html (3 von 8) [19.12.2006 13:49:30] Basic Commands and Language Structure with the page in some way. For example, when someone enters a value into a text box on a form or clicks a Submit button, a series of events is triggered inside the web browser. All these events can be intercepted by JavaScript programs. Functions Functions are similar to methods. The difference is that whereas methods are associated with built-in objects, functions are standalone routines that are embedded in the page. To define a function for the current web page, you would write something like this: <script language="JavaScript"> function functionName(arguments) { The actions to be performed by your function go here } </script> In this code, functionName is just about any unique name that you choose, and arguments is a list of any values that you want to be sent to the function. The only function names you can't choose are those that are already part of JavaScript. Following the function definition and inside the set of braces ( {}), you include the list of instructions that you want the function to perform. It could be a set of calculations, validation routines for a form, or just about anything else you can think of. Note JavaScript also includes a set of built-in objects and functions that enable you to perform mathematical operations, string manipulation, and date and time calculations. For a full list of built-in functions, refer to the online JavaScript documentation. Functions are the core unit of reuse in JavaScript. If you want to do something more than once, you put the code to do it in a function, and then call the function wherever you want to do that thing. For example, let's say you had two values, a first name and a last name, and you wanted to turn them into one value. You could use the following code every time you wanted to do that: fullName = firstName + " " + lastName; Or you could write a function to take care of it, like this: function makeFullName(firstName, lastName) { return firstName + " " + lastName; } The name of the function is makeFullName, and it has two arguments, firstName and lastName. It combines the two names using the + operator and returns the result. This code is pretty simple, and putting it in a function doesn't save much work. For more complex operations, creating a function makes more sense. Later in this lesson, you'll learn how to include external JavaScript files on your page, much like you file:///G|/1/0672328860/ch12lev1sec3.html (4 von 8) [19.12.2006 13:49:30] Basic Commands and Language Structure learned to link to external style sheets in Lesson 9, "Creating Layouts with CSS." You can put functions you commonly use in an external JavaScript file and link to that file from all of the pages that use the functions, saving yourself a lot of maintenance work if any of the functions need to be updated later on. Assigning Functions to Events After you define your functions, your next step is to assign them to the various events that you want to act on. You do so by assigning event handlers to the various elements of a web page or form. Currently, you can set the event handlers shown in Table 12.1. Table 12.1. JavaScript Event Handlers Event Handler When It's Called onblur Whenever a visitor leaves a specified form field onchange Whenever a visitor changes the contents of a specified form field onclick Whenever a visitor clicks a specified element onfocus Whenever a visitor enters a specified form field onload Whenever a web page is loaded or reloaded onmouseover Whenever a visitor places the mouse cursor over a specified object onselect Whenever a visitor selects the contents of a specified field onsubmit Whenever a visitor submits a specified form onunload Whenever the current web page is changed To specify functions that should be associated with any of these events, you just need to include the appropriate event handler as an attribute of the tag associated with that event. For example, consider a standard form with a couple of text fields and a Submit button, as shown here: <form method="post" src="/cgi-bin/form"> <input type="text" name="username"> <input type="text" name="emailAddress"> <input type="submit"> </form> Adding onsubmit="return checkform(this)" to the <form> tag causes the function called checkform() to be executed before the browser submits the form. In checkform(), you can perform any checks that you want and, if any problems occur, halt the form submission and ask the user to fix them. The this parameter inside the parentheses is used to tell the checkform() function which form object is associated with the <form> tag. file:///G|/1/0672328860/ch12lev1sec3.html (5 von 8) [19.12.2006 13:49:30] Basic Commands and Language Structure The Meaning of this You might be a bit puzzled by the use of this as an argument passed to a function. Here, this is shorthand for the current object. When you're using an event handler in a tag, this refers to the object represented by that tag. In the previous example, it refers to the form associated with the <form> tag in which it appears. Why use an argument at all? So that one function can be used with many objects. In this case, we might have four forms on the page that can all be validated using checkform(); we can distinguish between those forms by passing a reference to the form using this. In addition, you can do field-by-field checking by including either onchange or onblur event handlers in each <input> tag. Because the onblur handler is called each time a person leaves a field, it's ideal for input validation. Buttons such as the Submit button trigger the onclick event. For example, <input type="submit" onclick="processclick()"> calls the function processclick() whenever the Submit button is clicked. Variables In addition to properties, JavaScript also enables you to assign or retrieve values from variables. A variable is a user-defined container that can hold a number, some text, or an object. But unlike most high-level languages that force you to limit the contents of each variable to a specific type, JavaScript is a loosely typed language. This means that you don't need to specify the type of information that a variable can contain when you create it. In fact, data of different types can be assigned to the same variable, depending on your requirements. To declare a variable for a JavaScript program, you would write the following: var variablename = value ; In this form, variablename is a name that you choose. You can choose any name you like, as long as it's not already reserved as part of the JavaScript language. The equal sign ( =) following the variablename is called an assignment operator. It tells JavaScript to assign whatever is on the right side of the = sign valueas the contents of the variable. This value can be a text string, a number, a property, the results of a function, an array, a date, or even another variable. Here's an example: var name = "Laura Lemay"; var age = 28; var title = document.title; var documenturl = location.toString();var myarray = new Array(10); var todaysdate = new Date(); var myname = anothername; Note file:///G|/1/0672328860/ch12lev1sec3.html (6 von 8) [19.12.2006 13:49:30] . other languages, including Java. Still, JavaScript is a scripting language, which gives it a steeper learning curve than HTML (although JavaScript's curve isn't as steep as Java's) be annoying ways. For example, many sites open an additional window containing an advertisement when you navigate to one of their pages. This is accomplished using JavaScript and the page load. Commands and Language Structure Basic Commands and Language Structure JavaScript is an object-based language. It accesses the browser and elements on the page in an object- oriented fashion.

Ngày đăng: 07/07/2014, 09:20

Tài liệu cùng người dùng

Tài liệu liên quan