Event Processing
Event handling OverviewEvent processing is a very important part of object-oriented programming. Without event processing, the program will become very dead and lacks flexibility. The process of event processing can be like this: Event-start event handler-event handler to respond. To enable the event handler to start, you must first tell the object what handler to start if something happens. Otherwise, the process cannot proceed. The event handler can be any JavaScript statement, but we usually use a specific custom function to handle the event.
Specify the event handlerThere are three methods to specify an event handler:
Method 1It is specified directly in the HTML Tag. This method is the most common. The method is: <mark ...... event = "event handler" [event = "event handler"...]> let's take a look at the example: <body... onload = "alert ('webpage reading is complete, please enjoy it slowly! ') "OnUnload =" alert ('Goodbye! ') "> This definition <body> mark can pop up a dialog box saying" the webpage has been read successfully. Please enjoy it slowly "; when you exit a document (close a window or go to another page), "goodbye" is displayed ".
Method 2Compile JavaScript for specific events of a specific object. This method is rarely used, but it is useful in some scenarios. Method: <script language = "JavaScript" for = "object" event = "Event">
...
(Event handler code)
...
</SCRIPT> example: <script language = "JavaScript" for = "window" event = "onLoad">
Alert ('webpage reading is complete. Please enjoy it slowly! ');
</SCRIPT>
Method 3In JavaScript. Method: <event protagonist-Object>. <event >=< event handler>. In this method, you must note that "event handler" is real code, not string code. If the event handler is a custom function, do not add "()" If you do not need to use parameters. Example :...
Function ignoreerror (){
Return true;
}
...
Window. onerror = ignoreerror; // "()" is not used
In this example, the ignoreerror () function is defined as the onerror event handler of the window object. The result is to ignore any errors in the window object (the "no permission" error generated by referencing the location object that is not allowed to be accessed cannot be ignored ).
Event details
Onblur eventOccurs when the window loses focus.
Applied to: Window objects
Onchange eventThe content in the text input area is changed, and the focus is removed from the text input area. Capturing this event is mainly used to detect the input validity in real time or change the document content immediately.
Applies to: Password object; select object; Text object; textarea object
Onclick eventOccurs when an object is clicked. Clicking is a complete process of holding the mouse over the object and pressing the mouse key without moving the mouse. A normal button object (button) usually has an onclick event handler, because this kind of object cannot get any information from the user at all, without the onclick event handler is equivalent to the waste of wood. To add an onclick event handler to the button, you can simulate another commit button by modifying one or more attributes of the form, such as action, target, encoding, and method, in the event handler, then, call the submit () method of the form. Return false in The onclick event handler of The Link object to prevent the browser from opening the connection. That is, if there is a connection like this: <a href = "http://www.a.com" onclick = "Return false"> go! </A> the website does not go to www.a.com no matter how you click it, unless the browser is prohibited from running JavaScript.
Applies to: button object, checkbox object, image object, link object, Radio object, Reset object, and submit object.
Onerror eventWhen an error occurs. Its event handler is usually called an error handler to handle errors. As mentioned above, to ignore all errors, use: function ignoreerror (){
Return true;
}
Window. onerror = ignoreerror;
Applied to: Window objects
Onfocus eventOccurs when the window gets the focus.
Applied to: Window objects
Onload eventThis occurs when all documents are downloaded. After all the files are downloaded, not only HTML files, but also images, plug-ins, controls, applets, and other content are downloaded. This event is a window event, but when you specify an event handler in HTML, we write it in the <body> tag.
Applied to: Window objects
Onmousedown eventThis occurs when you place your mouse over an object and press the mouse key. Refer to the onmouseup event.
Applied to: button object; Link object
Onmouseout eventOccurs when the mouse leaves the object. Refer to the onmouseover event.
Applied to: link object
Onmouseover eventOccurs when the mouse enters the object range. This event and the onmouseout event, coupled with pre-reading, can achieve the effect of image changes when the mouse moves over the image connection. Sometimes we can see that when pointing to a connection, the status bar does not display the address, but other information, it seems that the information can be changed at any time. They do this: <a href = "..."
Onmouseover = "window. Status = 'click me please! '; Return true ;"
Onmouseout = "window. Status =''; return true; ">
Applied to: link object
Onmouseup eventThis occurs when you place the mouse on an object and press the mouse key. This event does not occur if the mouse is not on an object that is opened when you press the mouse key.
Applied to: button object; Link object
Onreset eventThis occurs when the "reset" button of the form is clicked (pressed and opened. Return false in the event handler to prevent form resetting.
Applied to: Form objects
Onresize eventThe window size is adjusted.
Applied to: Window objects
Onsubmit eventThis occurs when the "Submit" button of the form is clicked (pressed and opened. You can use this event to verify the validity of the form. Return false in the event handler to prevent form submission.
Applied to: Form objects
OnUnload EventOccurs when the user exits the document (or closes the window, or goes to another page. Like onload, it should be written in HTML and written into the <body> tag. Some web masters use this method to pop up the "Investigation Form" and fill it in as "forced"; some pop up the advertisement window, prompting the visitors to click the connection. I think this method of "onUnload =" open... "is very bad. Sometimes, too many windows are displayed, leading to lack of resources. What do you say to the recipient should be done on the webpage?
Applied to: Window objects
Statements about Object-Oriented ProgrammingNow we have the strength to learn the following object-oriented programming, but it actually belongs to the content of the previous chapter.
With statementSpecifies the default object for one or more statements. Usage: With (<Object>) <Statement>; with statements are usually used to shorten the amount of code that must be written in a specific situation. In the following example, pay attention to the repeated use of Math: x = math. Cos (3 * Math. Pi) + math. Sin (math. ln10 );
Y = math. Tan (14 * Math. E); when using the with statement, the Code becomes shorter and easier to read: With (math ){
X = cos (3 * PI) + sin (ln10 );
Y = tan (14 * E );
}
This objectReturns the "current" object. In different places, this indicates different objects. If this is used in the JavaScript "main program" (not in any function, not in any event handler), it represents the window object; if this is used in the with statement block, it indicates the object specified by with. If this is used in the event handler, it indicates the object where an event occurs. A common usage of this: <SCRIPT>
...
Function check (formobj ){
...
}
...
</SCRIPT> <body...>
...
<Form...>
...
<Input type = "text"... onchange = "check (
This. Form) ">
...
</Form>
...
</Body> This is often used to immediately check the validity of form input.
Custom ConstructorWe already know that constructors such as array () and image () allow us to construct a variable. In fact, we can also write our own constructor. User-Defined constructors also use functions. This is used in the function to define attributes. Function <constructor Name> [(<parameter>)] {
...
This. <attribute name >=< initial value>;
...
} Then, use the new constructor keyword to construct the variable: var <variable name> = new <constructor Name> [(<parameter>)]; after the variable is constructed, <variable name> to be an object, which has its own attributes-attributes set in the function using this. The following is an example of a custom constructor that collects browser details from the Internet: function is (){
VaR agent = navigator. useragent. tolowercase ();
This. Major = parseint (navigator. appversion); // main version
This. Minor = parsefloat (navigator. appversion); // full version
This. NS = (agent. indexof ('mozilla ')! =-1 )&&
(Agent. indexof ('spoofer ') =-1) & // whether it is Netscape
(Agent. indexof ('compuble ') =-1 )));
This. ns= (this. NS & (this. Major = 3); // whether Netscape 2
This. NS3 = (this. NS & (this. Major = 3); // whether Netscape 3
This. ns4b = (this. NS & (this. Minor <4.04); // check if the version is earlier than Netscape 4.
This. ns4 = (this. NS & (this. Major> = 4); // whether it is a high version of Netscape 4
This. Ie = (agent. indexof ("MSIE ")! =-1); // whether it is IE
This. ie3 = (this. ie & (this. Major = 2); // whether it is ie 3
This. ie4 = (this. ie & (this. Major> = 4); // whether it is IE 4
This. OP3 = (agent. indexof ("Opera ")! =-1); // whether it is opera 3
This. Win = (agent. indexof ("win ")! =-1); // whether the Windows version is used
This. Mac = (agent. indexof ("Mac ")! =-1); // indicates whether the Macintosh version is used.
This. UNIX = (agent. indexof ("X11 ")! =-1); // whether the unix version is used
}
VaR is = new is ();
This constructor collects browser information very completely. We can see that it defines many attributes for the object: Major, minor, NS, ie, win, Mac, and so on. Their meanings can be found in the preceding annotations. After defining the is variable as the is () object, you can easily know the browser information in the format of IF (is. NS. We can also see from this constructor that it can also use general JavaScript statements (VAR statements in the above example ). Let's look at a constructor using parameters: function myfriend (thename, gender, theage, birthon, thejob ){
This. Name = thename;
This. ismale = (gender. tolowercase = 'male ');
This. Age = theage;
This. Birthday = new date (birthon );
This. Job = thejob
} Var Stephen = new myfriend ('Stephen ', 'male', 18, 'dec 22,198 2', 'student'); from this constructor, we not only see the parameter usage, we can also see that different data types can be used for different attributes (in the preceding example, the five attributes are: String, Boolean value, number, date, string ), the constructor can also be used to "construct" attributes. If enough "protection measures" are used to avoid infinite loops, you can also use constructors to construct your own attributes.
Use framework and cookies
FrameworkWhen talking about the window object, we mentioned that a webpage in the framework is also a window object, that is, the frame object is also a window object. In the simplest case, each HTML file occupies a window object, including a webpage defining a framework ("framework webpage "). In IE, "<IFRAME>" is used to mark the framework inserted in the document as a window object, but "include webpage" is used (displayed as "<! -- Webbot bot = "include"... --> ") the HTML read does not occupy the window object alone. Every frame is a child object of the window object that contains its page (I do not know whether it should be called "attribute" or not). To reference it, you can use one of the following methods: window. frames [x]
Window. Frames ['framename']
Window. framename where X refers to the framework specified in the window object. Like other arrays, X also starts from scratch. Framename refers to the Framework name, which is the same as the "name" attribute in <frame>. If the window object specified by window. framename is a framework webpage, the method for referencing the framework is window. framename. subframename. And so on. Note that, no matter where the object is, all objects returned by referencing the "window" object are "current" window objects. If you want to access other window objects, you need to use the parent and top attributes. Parent refers to the "parent" window object, that is, the frame webpage that contains the current window object; top refers to the window object at the top of the window. You should also pay close attention to the global variables and user-defined functions defined in your JavaScript. They all have their own -- the window object. To reference global variables or udfs in other frameworks, you must use "window objects. Framework objects [. Framework objects…]. Global variables or user-defined functions. The above problem is often ignored when establishing a connection: if a default target window (<base target = "... ">) in <a href =" javascript :... ">, you must know that the entered JavaScript statement is run in the default target window. If necessary, add the" parent "and" TOP "attributes.
Use cookiesWe already know that there is a cookie attribute in the Document Object. But what is Cookie? "Some websites store some information on your hard disk with small text files, which are called cookies ." -- MSIE help. In general, cookies are created by CGI or similar files and programs that are more advanced than HTML, but JavaScript also provides comprehensive access rights to cookies. Before continuing, we must first learn
Basic cookie knowledge. Each cookie is like this: the <cookie name >=< value> <cookie Name> restriction is similar to the Javascript naming restriction, with the missing "cannot use JavaScript keywords ", "Only characters that can be used in URL encoding can be used ". The latter is hard to understand, but as long as you only use letters and numbers for naming, there is no problem at all. The <value> requirement is "only characters that can be used in URL encoding ". Each Cookie has an expiration date. Once the computer clock expires, the cookie will be deleted. You cannot delete a cookie directly, but you can delete it indirectly by setting the expiration date earlier than the current time. Each webpage, or site, has its own cookies. These cookies can only be accessed by webpages under the site, from webpages in other sites or in unauthorized areas under the same site, is inaccessible. Each "group" Cookie has a specified total size (about 2 kb per "group"). If the total size exceeds the maximum size, the first invalid cookie is deleted first, to make the new cookie "home ". Now let's learn
Use document. Cookie attributes. If you directly use document. cookie attribute, or use a method such as assigning values to variables to obtain the document. cookie value, we can know the number of cookies in the current document, the name of each cookie, and its value. For example, add "document. write (document. cookie), the result is: Name = Kevin; email = kevin@kevin.com; lastvisited?index.html which means that the document contains three cookies: name, email, and lastvisited, whose values are Kevin, A kevin@kevin.com and index.html. We can see that two cookies are separated by semicolons and spaces, so we can use cookiestring. the split (';') method returns an array separated by each cookie (VAR cookiestring = document first. cookie ). To set a cookie, assign a value to document. Cookie. Unlike other conditions, assigning values to document. Cookie does not delete the original cookies, but only adds or modifies the original cookies. Assignment format: Document. Cookie ='
Cookiename= '+
Escape('
Cookievalue')
+'
;Expires = '+
Expirationdateobj.
Togmtstring ()Are you dizzy? The above is not the place where the bold text is to be copied without mistake, the bold text is to be changed according to the actual situation. Cookiename indicates the cookie name, cookievalue indicates the cookie value, and expirationdateobj indicates the date object name storing the expiration date. If you do not need to specify the expiration date, the second row is not required. If no expiration date is specified, the browser expires after the browser is closed (that is, all windows are closed) by default. Have you seen the underline above? These are important points.
First, the escape () method: Why must it be used? Because the cookie value must be "only characters that can be used in URL encoding ". We know that the "escape ()" method is to encode the string by URL encoding, then we only need to use an "escape ()" method to process the value output to the cookie, you can use "scape SCAPE ()" to process the values received from cookies. The most common use of these two methods is to process cookies. In fact, setting a cookie is just "document. cookie = 'cookiename = cookievalue '"is so simple, but it is better to use an escape () to avoid any characters in the URL in cookievalue.
Then the semicolon before "expires" is noted. It is a semicolon rather than a semicolon.
Finally, togmtstring () method: Set the Cookie's validity period date to use the GMT format, and other formats of time do not work. Now let's take a look. Set a cookie named "name = rose" and expire three months later. VaR expires = new date ();
Expires. settime (expires. gettime () + 3*30*24*60*60*1000 );
/* Three months x one month treated as 30 days x 24 hours a day
X hour 60 Minutes x minute 60 seconds x second 1000 ms */
Document. Cookie = 'name = rose; expires = '+ expires. togmtstring (); why not use the escape () method? This is because we know that Rose is a legal URL encoded string, that is, 'Rose '= escape ('Rose '). Generally, if you do not use escape () when setting a cookie, you do not need to use Unescape () when obtaining the cookie (). Next time: Write a function to find the value of the specified cookie. Function getcookie (cookiename ){
VaR cookiestring = Document. Cookie;
VaR start = cookiestring. indexof (cookiename + '= ');
// The reason for adding the equal sign is to avoid having
// The same string as cookiename.
If (START =-1) // cannot be found
Return NULL;
Start + = cookiename. Length + 1;
VaR end = cookiestring. indexof (';', start );
If (END =-1) return Unescape (cookiestring. substring (start ));
Return Unescape (cookiestring. substring (START, end ));
} This function uses some methods of the string object. If you do not remember (Are you so unremembered?), please check it out. All the IF Statements of this function do not contain the else. This is because if the condition is true, the program runs the return statement, and the operation stops when the return statement is run in the function, so it's okay if you don't add Else. When this function finds the cookie, it will return the cookie value; otherwise, "null" is returned ". Now we want to delete the name = rose cookie we just set. VaR expires = new date ();
Expires. settime (expires. gettime ()-1 );
Document. cookie = 'name = rose; expires = '+ expires. togmtstring (); you can see that you only need to change the expiration date to a point earlier than the current date (this is 1 millisecond earlier), and then set the cookie in the same way to delete the cookie.