Recently collected some methods about JavaScript binding events, summarized, not comprehensive, but, I hope to facilitate the future to see for themselves.
There are three main ways to bind events in javascript:
1 binding directly in a DOM element
2 Direct binding in JavaScript code
3 Bound Event listener function
First, bind directly in the DOM element
That is, directly in the HTML tag by onxxx= "" to bind. As an example:
<input type= "button" value= "dot I Yo" onclick= "alert (" Hello world! ")" />
<!--or-->
<input type= "button" value= "dot Me Yo" onclick= "Testalert ()" >
<script type= " Text/javascript ">
function Testalert () {
alert (" Hello world! ");
}
</script>
Two, direct binding in JavaScript code
In JavaScript, by looking up a DOM object, bind it to it, Elementobject.onclick=function () {} 's format, for example:
<input type= "button" value= "point I Yo" id= "demo" >
<script type= "Text/javascript" >
document.getElementById ("Demo"). Onclick=function Testalert () {
alert ("Hello world!");
}
</script>
Third, binding event listening function
Here you need to know the function syntax for AddEventListener () and attachevent ().
1 Elementobject.addeventlistener (Eventname,handle,usecapture) (support for mainstream browsers, as well as IE9.0 and above)
EventName: The name of the event to bind. Note the writing, such as click Events, write click, not onclick.
Handle: The name of the function that handles the event. But there is no parenthesis on the writing.
Usecapture:boolean type, whether to use capture, general use false, the specific involved will be summed up in the rear.
2 elementobject.attachevent (Eventname,handle); (only IE8 and below)
A good way to find a compatible solution from the Internet is to compare if. Else statement, this method is using a try ... Catch error-handling statements to prevent the browser from having an error message.
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
}
}
}
Four, talk about several methods of binding events in jquery.
mainly on (), Bind (), Live (), delegate () and so on, the corresponding binding is off (), Unbind (), Live (), undelegate ();
1 on (), Bind (), Live (), delegate (), in addition to bind (), the others can add binding events to the element objects that are appended later.
2 Each of these methods has a version of jquery that corresponds to the support.
3 When you bind events to dynamically added page elements, you typically use the on () method.
The above is a small series for everyone on the JavaScript event binding method Summary of all the content, I hope that we support cloud Habitat Community ~