In this\texampl","url":"https://123docz.net/document/5358794-premier-press-learn-javascript-in-a-weekend-second-edition.htm","image":"https://media.store123doc.com/images/document/2019_03/26/larger_cxs1553595218.jpg","headline":"Premier Press Learn JavaScript In a Weekend Second Edition","datePublished":"2019-03-29","dateModified":"2024-01-09"} In this\texampl","url":"https://123docz.net/document/check-download/5358794","encodingFormat":"application/pdf","publisher":{"@type":"Organization","name":"123doc"},"datePublished":"2019-03-29","thumbnailUrl":"https://media.store123doc.com/images/document/2019_03/26/larger_cxs1553595218.jpg"}
  1. Trang chủ
  2. » Thể loại khác

Premier Press Learn JavaScript In a Weekend Second Edition

14 43 0

Đ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

Định dạng
Số trang 14
Dung lượng 318,27 KB

Nội dung

Handling Events Until now, most of the JavaScripts you have seen have executed in a top-tobottom manner By this, I mean that the browser begins executing your script as soon as the page loads, beginning with the first JavaScript statement and moving on to the succeeding statements until the last statement is processed The one exception to this was the use of functions placed in the head section of the page or at the top of the body section and executed by functions calls later in the script In some cases, the addition of an if then statement or a switch statement might have made the execution of a statement or function optional But even in these cases where multiple logical paths of script execution exist, the script statements execute logically in a serial fashion Defining Events In JavaScript, an event occurs within the confines of the browser Events include such activities as mouse clicks, mouse movement, pressing keyboard keys, the opening and closing of windows and frames, and the resizing of windows Browsers recognize events and perform default actions when those events occur For example, when a user clicks on a link, the onClick event occurs, and the browser's default action is to load the Web page or image specified by the link To make your Web pages really interactive, you must add another tool to your scripting skill set: event handlers An event handler is a trap that recognizes the occurrence of a particular type of event You can add code to your scripts that alters the browser's default response to events For example, instead of automatically loading the URL specified by a link, you could display a confirmation dialog box that asks the user to agree to certain terms before proceeding NOTE The names of event handlers are based on the events that trigger them Placing the word on in front of the event name creates the event handler's name For example the event handler for the click event is onClick Each event is associated with a specific object When an event occurs for a given object, its event handler executes (assuming that you have written one) For example, the click event occurs whenever a user clicks on a button, document, check box, link, radio option, reset button, or submit button Event handlers are surprisingly easy to define considering their power You place them within HTML tags that define the object For example, you can define an event to occur whenever a Web page is loaded by placing an onLoad event handler inside the first HTML tag as shown here: In this example, an alert dialog appears when the page finishes loading Notice that the event handler comes immediately after the tag and that its value is placed within quotation marks You can use any JavaScript statement as the value for the event handler You can even use multiple statements, provided that you separate them with semicolons Alternatively, you can use a function call, which enables you to perform more complex actions in response to the event You will see plenty of examples of how and where to place event handlers in various types of HTML tags throughout the rest of this session NOTE See Appendix B,"A Summary of JavaScript Events and Event Handlers,"for a complete list of events, event handlers, and objects to which specific events apply The event Object The event object is populated on every occurrence of an event The information in its properties can be referenced by event handlers, giving your script access to detailed information about the event For example, the event.modifiers property specifies any modifier keys that were associated with a mouse or keyboard event If the user pressed the Alt key while clicking the mouse button, the event.modifiers property contains the value Alt The event.type modifier contains a string representing the type of event that occurred, and the event.which modifier contains a number that specifies the mouse button that was pressed or the ASCII value of the keyboard key that was pressed Types of Events JavaScript currently supports 24 different events and event handlers These events can be broadly divided into a few categories: Window and frame events Mouse events Keyboard events Error events A number of these events and their associated event handlers are demonstrated in the scripts that follow For a complete list of events and event handlers, see Appendix B Window and Frame Events Events that affect window and frame objects include the load, resize, unload, and move events The event handlers for these events are onLoad, onResize, onUnload, and onMove These event handlers are placed inside the tag The following script uses the alert() method to demonstrate how to execute JavaScript statements in response to occurrences of these events: Script 3.13 - onLoad, onResize, onUnload & onMove Example

Type a few characters and then click on the button:

The script defines a simple form that consists of two elements: a TEXTAREA field and a button The onKeyDown event handler is used to keep track of the total number of keystrokes typed by the user in the TEXTAREA field The onKeyDown event is set to trigger each time the user types a new keystroke It calls the CountKeyStrokes() function, which adds 1 to a variable called totalKeyStrokes This variable stores a running total of the current number of keystrokes made by the user When the user clicks on the form's button, a pop-up dialog is displayed that shows the total number of keystrokes entered so far by the user NOTE The event object's event.which property specifies the ASCII value of the key pressed or the ASCII value of the mouse button that was clicked Figure 3.20 demonstrates what happens when you run the script, enter a few words in the TEXTAREA field, and then click on the form's button Figure 3.20 Using the onKeyDown event handler to count keystrokes Error Events An error event occurs whenever your JavaScripts run into an error Error events automatically trigger the onerror event By adding an onerror event handler to your scripts, you can intercept these errors and suppress them After they are suppressed, you then can either attempt to fix them programmatically or display a customized error message NOTE Unlike other event handlers, the onerror event handler is spelled in all lowercase The onerror event handler automatically receives three arguments when it is triggered: the error message itself, the URL of the Web page, and the line number in the script where the error occurred You can use the onerror event handler to respond to the error For example, you can display an alert prompt, redirect the user to another Web page, call a function, advise the user to upgrade the browser or get a specific plug-in, and so on The onerror event handler works a little differently than other event handlers and has the following syntax window.onerror=FunctionName Note that the spelling of the onerror event handler is in all lowercase and that it is not embedded within HTML tags like other event handlers Instead, it is defined within the tags as a JavaScript statement When triggered, the onerror event handler calls a function However, the matching pair of parentheses are left off of the end of the function call When used, the onerror event handler is set up in the head section of the HTML page, along with its associated function The following script demonstrates how to use the onerror event handler to display error information using a function called ErrorTrap() This function accepts three arguments that map to the three arguments passed to the onerror event handler The function uses these arguments to format three lines of text that present the error information To produce an error on the page, I deliberately added an s to the end of the word window in the HTML page's body tag windows is a not a valid browser object Script 3.17 - onError Example Welcome to my Web page NOTE Note the return true; statement at the end of the ErrorTrap function in the previous example This statement tells the browser to suppress the error Figure 3.21 shows the results of loading this script using Internet Explorer As you can see, the message written to the window tells you what the error was, where in the Web page the error occurred, and where the page is located Figure 3.21 Trapping errors with the onerror event handler The onerror event hander can also be used within HTML tags By placing the onerror event handler within a particular HTML tag, you can define different actions for error events on an object-by-object basis For example, the following JavaScript uses this technique to create an error message in the event that the specified graphic file cannot be found Script 3.18 - Another onError Example Figure 3.22 shows the results of loading the previous script An alert prompt is immediately displayed when the browser fails to locate the specified xxxx.jpg image file Figure 3.22 Using the onerror event handler to report problems when loading an image Using the onClick Event as a Decision Point Before wrapping up the first half of this afternoon, I want to show you a neat little trick using links and the onClick event handler In the example that follows, I defined a link to a Web site to which I added the onClick event Inside the event handler, I used the window.confirm() method to ask the user for confirmation before enabling the browser to load the link The window.confirm() prompt gives the user two options Clicking on OK returns a value of true, which enables the browser to load the Web page; clicking on Cancel returns a value of false, which prevents the browser from loading the specified URL Script 3.19 - Age Verification Example ptpmagazine.com NOTE TIP You can use a variation of this example to ask users whether they are sure they want to leave your Web site when they click on links Figure 3.23 shows what happens if you load the preceding page Figure 3.23 Verifying a user's age before allowing him into your Web site ... ... In this example, an alert dialog appears when the page finishes loading Notice that the event handler comes immediately after the tag and that its value is placed within quotation marks You can use any JavaScript statement as the value for the event handler... event to occur whenever a Web page is loaded by placing an onLoad event handler inside the first HTML tag as shown here: In this example, an alert dialog appears when the page finishes loading

Ngày đăng: 26/03/2019, 17:13