First introduce the general method of adding events by js. The specific content is as follows
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p id="p1">Test Add Event: firefox uses addEventListener, ie uses attachEvent<br> Click this p tag, and 2 pop-up events are bound</p> <script> function test1() { alert("test1"); } function test2(){ alert("test2"); } //Add event general method function addEvent(element,e,fn) { //Firefox uses addEventListener to add event if(element.addEventListener) { element.addEventListener(e,fn,false); } //ie use attachEvent to add event else { element.attachEvent("on"+e,fn); } } window.onload = function(){ var element = document.getElementById("p1"); addEvent(element,"click",test1); addEvent(element,"click",test2); } </script> </body></html>Common ways to bind js events:
How to bind events: bind event functions with event attributes
advantage:
1. Complete the separation of behaviors
2. It is convenient for operating the object involved, because function appears as an on*** attribute, you can directly refer to the object involved using this.
3. Easy to read event objects. When the event is triggered, the system will automatically pass the event object to the event function, and one of them will be passed.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>JS event binding</title> <script type="text/javascript"> window.onload=function(){ var k=document.getElementById('k').onclick=function(event){ var jj=document.getElementById('jj'); jj.style.top=event.clientX+'px'; jj.style.left=event.clientY+'px'; } } </script> <style> #k{width:60px;height:80px; background-color:#80ffff;} #jj{width:60px ;height:80px;background-color:#ffff00;z-index:1000;position:absolute;} </style> </head> <body> <div id="k"></div> <div id="jj"></div> </body> </html>The above is all about this article, I hope it will be helpful to everyone's learning.