First introduce the common method of adding events in js, the specific content is as follows
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p id="p1">测试添加事件:firefox使用addEventListener,ie使用attachEvent<br> 点击此p标签,绑定了2个弹出事件</p> <script> function test1() { alert("test1"); } function test2(){ alert("test2"); } //添加事件通用方法 function addEvent(element,e,fn) { //firefox使用addEventListener,来添加事件 if(element.addEventListener) { element.addEventListener(e,fn,false); } //ie使用attachEvent,来添加事件 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>
The common way of binding events in js:
How to bind events: Use event attributes to bind event functions
Advantages:
1. Complete the separation of behaviors
2. It is convenient to operate the object in question, because the function is Appearing as an attribute of on***, you can directly use this to refer to the object in question.
3. It is convenient to read the event object. When the event is triggered, the system automatically passes the event object to the event function. Pass it one by one
<?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事件绑定</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> <p id="k"></p> <p id="jj"></p> </body> </html>
The above is the detailed content of Detailed explanation of how to use event attributes to bind event functions in javascript. For more information, please follow other related articles on the PHP Chinese website!