<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin:0; padding:0; } h1{ background:red; } p{ background:greenyellow; } </style> </head> <body> <input type="button" value="添加p" id="btn1"> <input type="button" value="添加h1" id="btn2"> <div id="div"> <h1>rua i am h1</h1> <p>rua i am p</p> </div> <script> window.onload=function(){ function addEvent(odiv,eve,fn,boll){//事件监听的兼容 if(odiv.addEventListener){ odiv.addEventListener(eve,fn,boll); } else if(odiv.attachEvent){ odiv.attachEvent("on"+eve,fn); } } var oBtn_1=document.getElementById("btn1"); var oBtn_2=document.getElementById("btn2"); var oDiv=document.getElementById("div"); var rua_1=2; var rua_2=2; oBtn_1.onclick=function(){ var oP=document.createElement("p"); oP.innerHTML="i am p"+rua_1; oDiv.appendChild(oP); rua_1++; } oBtn_2.onclick=function(){ var oH1=document.createElement("h1"); oH1.innerHTML="i am h1"+rua_2; oDiv.appendChild(oH1); rua_2++; } addEvent(oDiv,"click",function(ev){ var oEvent=ev||window.event; var rua=oEvent.target||oEvent.srcElement; alert(rua.innerHTML); }); } </script> </body> </html>
低版本的IE和高版本IE,firefox,chrome事假机制的区别
低版本IE:2参数,attachEvent 事件监听,detachEvent移出事件
高版本IE,firefox,chrome:addEventListener事件监听,removeEventListener移除事件
事件监听兼容
function addEvent(odiv,eve,fn,boll){//事件监听的兼容 if(odiv.addEventListener){ odiv.addEventListener(eve,fn,boll); } else if(odiv.attachEvent){ odiv.attachEvent("on"+eve,fn); } }