"Add event mechanism" AddEventListener and attachevent
[The]
AddEventListener (' click ', function () {alert (' Hello World ')}, FALSE)//W3C specification add event (IE8 and above incompatible); The first argument is the event type, the second is the event program, and the third F Alse for event bubbling, true for event capture
[IE]
Attachevent (' onclick ', function () {alert (' Hello World ')})//ie add event; The first parameter is the event type (need to be added on); The second is an event program; because IE only supports event bubbling, only two parameters
[Cross-browser compatible]
function Insertevent (obj,event,fun) {
if (Obj.addevenlistener) {
Addeventlitener (Event,fun,false)
}else if (Obj.attach) {
Attachevent (' on ' +event,fun)
}
}
------------------------------------------------------------------------------------------
"Delete event mechanism" RemoveEventListener detachevent
[RemoveEventListener]
RemoveEventListener ()//Use AddEventListener new events can only be removed by RemoveEventListener;
[note]//The following is a bad way to delete an event because the event program must not be an anonymous function
AddEventListener (' click ', function () {alert (' Hello World ')}, False)
RemoveEventListener (' click ', function () {alert (' Hello World ')},false)
Solution
AddEventListener (' Click ', box, false);
RemoveEventListener (' click ', Box,false);
function box () {
Alert (' Hello world ');
}
[Cross-browser compatible]
function Deleteevent (obj,event,fun) {
if (Obj.removeeventlistener) {
RemoveEventListener (Event,fun,false);
}else if (obj.detachevent) {
DetachEvent (' on ' +event,fun)
}
}
-------------------------------------------------------------------------------------------------
"Block default behavior for specific events"
[Preventdefault and ReturnValue]
[Preventdefault]
[IE] Reutrnvalue
[Cross-browser compatible]
function (event) {
event=event | | window.event;
if (Event.preventdefault) {
Event.preventdefault ()
}else{
Event.returnvalue=false;
}
}
---------------------------------------------------------------------------------------------------
"Get target Object"
[Target and Srcelement]
function (event) {
event=event | | window.event;
if (event.target) {
return event.target;
}else if (event.srcelement) {
return event.srcelement;
}
}
JavaScript event mechanism compatible with "grooming"