Web applications often use Javascript to process some things on the page. We don't need to talk about form verification. We need to deal with the DOM tree of the page when displaying/hiding or executing a js function based on the user's usage. Take a look at Gmail, send an email, press the "send" button, and then use Ajax to send the email content at the backend. Based on the returned status, a short text "your email has been sent" is displayed directly at the top of the editing page. ".
In general, we will write in the send button:
Onclick = "javascript: sendmail ();"
And then it will handle it. After Ajax is returned, another show_status () is triggered to provide relevant status information in the id = status object. For complex applications, the source code is full of html and js. It is not easy to maintain or flexible enough. By default, XHTML is only used to represent a DOM tree in the presentation layer, while JS performs some operations on this tree. It's not good to be confused.
Now we have addEvent () and removeEvent (). The problem is simple. For a dom object, it gives the event type and the function to be triggered, and the world is quiet. You can remove it at any time to handle a new event. This simplifies a lot of code. Quirksmode won the first place in the competition, and ejohn won the first place. His implementation is the simplest and clearest among all the participants. He gave related explanations and demos on his blog.
AddEvent (object, eventType, function );
AddEvent (document. getElementById ('foo'), 'click', doSomething );
AddEvent (obj, 'mouseover', function () {alert ('Hello! ');});
Before using it, copy the following code:
Function addEvent (obj, type, fn ){
If (obj. attachEvent ){
Obj ['E' + type + fn] = fn;
Obj [type + fn] = function () {obj ['E' + type + fn] (window. event );}
Obj. attachEvent ('on' + type, obj [type + fn]);
} Else
Obj. addEventListener (type, fn, false );
}
Function removeEvent (obj, type, fn ){
If (obj. detachEvent ){
Obj. detachEvent ('on' + type, obj [type + fn]);
Obj [type + fn] = null;
} Else
Obj. removeEventListener (type, fn, false );
}