Recently gathered some of the methods of JavaScript binding events, summarized, not comprehensive, but I hope it is easy to view later.
There are three main ways to bind events in javascript:
1 binding directly in DOM elements
2 Direct binding in JavaScript code
3 Binding Event Listener function
First, bind directly in the DOM element
That is, directly in the HTML tag through the onxxx= "" to bind. As an example:
<inputtype= "button"value= "point Me yo"onclick= "alert" ("Hello world! ")"/><!--or -<inputtype= "button"value= "point Me yo"onclick= "Testalert ()"><Scripttype= "Text/javascript"> functionTestalert () {alert ("Hello world!"); }</Script>
Second, direct binding in JavaScript code
In JavaScript, by finding the DOM object, bind it to the format of theelementobject.onclick=function () {} , for example:
<inputtype= "button"value= "point Me yo"ID= "Demo"><Scripttype= "Text/javascript">document.getElementById ("Demo"). onclick=functionTestalert () {alert ("Hello world!"); }</Script>
Third, the binding event listener function
Here you need to understand the function syntax of AddEventListener () and attachevent ().
1 elementobject.addeventlistener (eventname,handle,usecapture) (support for mainstream browsers, and IE9.0 and above)
EventName: The name of the event to bind. Note the notation, such as clicking on an event, written as Click instead of the onclick.
Handle: The name of the function that handles the event. But there are no parentheses in the notation.
Usecapture:boolean type, whether to use capture, generally with false, the specific involved will be summarized behind.
2 elementobject.attachevent (Eventname,handle); (only IE8 and below are supported)
Find a good way to be compatible from the Internet, compared to If. Else statement, this method uses a try: Catch error-handling statements to avoid browser error prompts.
function addevent (obj,type,handle) { try{ obj.addeventlistener (Type,handle,false ); } Catch (e) { try{
Obj.attachevent (' on ' +type,handle);
} Catch (e) {
obj[' on ' + type]=handle; // Early Browser
} }}
Iv. talk about several methods of binding events in jquery.
There are mainly on (), Bind (), Live (), delegate (), and so on, the corresponding Unbind is off (), Unbind (), Live (), undelegate ();
1 on (), Bind (), Live (), delegate () In addition to bind (), the other can add a binding event to an element object that is subsequently appended.
2 Each of these methods has a corresponding supported jquery version.
3 The On () method is typically used when binding events to dynamically added page elements.
For more specific information, you can click on this link http://www.cnblogs.com/DemoJin/p/4794372.html.
Summary of methods for event binding in JavaScript