Javascript event handler, javascript event processing
Javascript event handler 1. Common event handler
<input type="button" value="click me" onclick="showMessage()" />
function showMessage(){alert("clicked");}
2. DOMO-level event handler
<Span style = "white-space: pre"> </span> // The old var btn = document. getElementById ("myBtn"); // The dom Extension Method supports mainstream browsers, similar to jquery syntax var btn = document. querySelector ("# myBtn"); btn. onclick = function () {alert ("clicked! ");};
3. The DOM2-level event handler mainly introduces this, and we should be familiar with the above two events. The DOM2 event handler defines two methods for adding and deleting Event Handlers: addEventListener () and removeEventListener (). All DOM nodes contain these two methods. They have three parameters: the name, function, and Boolean value of the event to be processed (true capture stage execution, false bubble stage execution). In general, set false as an example:
var btn=document.getElementById("myBtn"); btn.addEventListener("click",function(){ alert("clicked!"); },false);
// The input removeEventListener parameter must be the same as addEventListener btn. removeEventListener ("click", function () {// it will not be executed here -- alert ("clicked! ") ;}, False );
IE implements two similar methods: attachEvent () and detachEvent (). Two parameters are accepted. There are no eight bool values:
var btn=document.getElementById("myBtn"); btn.attachEvent("onclick",function(){ alert("clicked"); });
btn.detachEvent("onclick",function(){ alert("clicked"); });
Therefore, we have also written a cross-browser event handler:
// 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 for other elements of IE. removeEventListener (type, handler, false);} else if (element. detachEvent) {// IEelement. detachEvent ("on" + type, handler);} else {element ["on" + type] = handler ;}}}