Note: This section describes cross-platform events in Chapter 9th of JavaScript advanced programming.
JS Add/delete events in IE and dom browsers are: attachEvent (add event in ie), detachEvent (delete event in ie), and addEventListener (add event in dom browser ), removeEventListener (supports deletion events in the dom browser ).
For example, when you click the black area for the first time, a warning is displayed, and the click event is removed. That is, the second click does not respond. The integrated code is as follows:
========================================================== =
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Add deletion event </title>
<Script type = "text/javascript">
Var EventUtil = new Object;
// OTarget: Target; sEventType: event name; funName: name of the function triggered by the event;
EventUtil. addEvent = function (oTarget, sEventType, funName ){
// Document. getElementById ("dd"). attachEvent
If (oTarget. addEventListener) {// for DOM;
OTarget. addEventListener (sEventType, funName, false );
} Else if (oTarget. attachEvent ){
OTarget. attachEvent ("on" + sEventType, funName );
} Else {
OTarget ["on" + sEventType] = funName;
}
};
EventUtil. removeEvent = function (oTarget, sEventType, funName ){
// Document. getElementById ("dd"). attachEvent
If (oTarget. removeEventListener) {// for DOM;
OTarget. removeEventListener (sEventType, funName, false );
} Else if (oTarget. detachEvent ){
OTarget. detachEvent ("on" + sEventType, funName );
} Else {
OTarget ["on" + sEventType] = null;
}
};
Function removeClick (){
Alert ("click ");
Var oDiv = document. getElementById ("odiv ");
ODiv. style. cursor = "auto ";
EventUtil. removeEvent (oDiv, "click", removeClick );
}
// ---- Bind multiple functions to window. onload ------//
Function addLoadEvent (func ){
Var oldonload = window. onload;
If (typeof window. onload! = "Function "){
Window. onload = func;
} Else {
Window. onload = function (){
Oldonload ();
Func ();
}
}
}
AddLoadEvent (addClick );
Function addClick (){
Var oDiv = document. getElementById ("odiv ");
ODiv. style. cursor = "pointer ";
EventUtil. addEvent (oDiv, "click", removeClick );
}
</Script>
</Head>
<Body>
<P> A warning is displayed when you click the black area for the first time, and the click event is removed. That is, the second click does not respond. </p>
<Div id = "odiv" style = "background: #333; height: 100px; width: 100px; margin: 0 auto; color: # CDCDCD; "> I warned you for the first time, and I ignored you for the second time! </Div>
</Body>
</Html>