JavaScript event handlers 1, normal event handlers
<input type= "button" value= "click Me" onclick= "ShowMessage ()"
function ShowMessage () {alert ("clicked");}
2, DOMO level Event processing program
<span style= "White-space:pre" ></span>//old method var Btn=document.getelementbyid ("MyBtn"); The DOM extension method supports mainstream browsers, similar to the jquery syntax var btn=document.queryselector ("#myBtn"); Btn.onclick=function () { alert ("clicked!"); };
3, the DOM2 level event processing program mainly introduces this. The top two people should be very familiar with it. The DOM2 event handler defines two methods for adding and removing event handler actions: AddEventListener () and RemoveEventListener () All DOM nodes include both methods, and they have 3 parameters: the name of the event to be processed, the function, Boolean (True Capture stage run, false bubbling stage run), General fill false Example:
var Btn=document.getelementbyid ("Mybtn"); Btn.addeventlistener ("click", Function () {alert ("clicked!");},false);
The input removeeventlistener must be the same as the AddEventListener Btn.removeeventlistener ("click", Function () {//This will not run no utility--alert (" Clicked! ");},false);
IE implements two similar methods: Attachevent () and DetachEvent (), accepting two of the parameters. There are no eight examples of bool values:
var Btn=document.getelementbyid ("Mybtn"); Btn.attachevent ("onclick", function () { alert ("clicked"); });
Btn.detachevent ("onclick", function () { alert ("clicked"); });
So we've also written a cross-browser event handler on this side:
Cross-browser event handler var eventutil= {addhandler:function (Element,type,handler) {if (Element.addeventlistener) { Element.addeventlistener (Type,handler,false);} else if (element.attachevent) {element.attachevent ("on" +type,handler);} else{element["on" +type]=handler;}},removehandler:function (Element,type,handler) {if (Element.removeeventlistener ) {//except IE other element.removeeventlistener (type,handler,false);} else if (element.detachevent) {//ieelement.detachevent ("on" +type,handler);} else{element["on" +type]=handler;}}}
JavaScript event handlers