看代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加事件的几种方法</title> <style type="text/css"> div{ width: 200px; height: 100px; background: #CCCCCC; border: 1px solid #008000; /*display: inline-block;*/ float: left; margin-top: 0; } </style> </head> <body> <div id="box1" onclick="event1()"></div> <div id="box2"></div> <div id="box3"></div> <div id="box4"></div> </body> <script type="text/javascript"> var box1 = document.getElementById("box1"); var box2 = document.getElementById("box2"); var box3 = document.getElementById("box3"); var box4 = document.getElementById("box4"); //行内绑定点击事件 function event1(){ box1.innerHTML = "你点我了"; } //节点绑定点击事件 box2.onclick = function(){ this.innerHTML = "你点我了"; } box2.onclick = function(){ this.innerHTML += "<br>" + "你点我了哦"; } //2级DOM事件绑定 绑定的处理函数都会执行 顺序<strong><span style="color:#ff0000;">由前向后</span></strong>依次执行 box3.addEventListener("click",function(){ this.innerHTML = "你点我了" },false); box3.addEventListener("click",function(){ this.innerHTML += "<br>" +"你点我了哦" },false); // IE绑定事件 绑定的函数都会执行 顺序<strong><span style="color:#ff6666;">由后向前</span></strong>依次执行 //现在好多浏览器已经不支持了 坑!!!!! if(box4.attachEvent){ box4.attachEvent("onclick",function(){ this.innerHTML = "你点我了"; }); box4.attachEvent("onclick",function(){ this.innerHTML += "<br>" + "你点我了啊" }); } <span style="white-space:pre"> </span> if (window.attachEvent) { <span style="white-space:pre"> </span>alert("支持attachEvent"); <span style="white-space:pre"> </span> } else { <span style="white-space:pre"> </span>alert("不支持attachEvent"); <span style="white-space:pre"> </span> } </script> </html>