event是ie自带的一个对象,而ff中不存在该对象,只能通过传递参数的方式来模拟event
另外ie中使用srcElement去获得事件触发源,ff下使用target。因此使用这两个对象时需要做相关的浏览器兼容。
复制代码 代码如下:
<!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=gb2312" />
<title>srcElement --http://www.jb51.net/</title>
<script type="text/javascript">
<!--
function Click(event){
event = event? event: window.event
var obj = event.srcElement ? event.srcElement:event.target;
alert(obj.tagName);
}
//-->
</script>
</head>
<body>
<button id="btn" onclick="Click(event)">点击</button>
</body>
</html>
查看运行结果
综合上节attachEvent与addEventListener。
复制代码 代码如下:
<script type="text/javascript">
<!–
function Click(event){
event = event? event: window.event;
var obj = event.srcElement ? event.srcElement:event.target;
alert("eventObj.tabName:" + obj.tagName);
}
var oBtnNew;
window.onload=function(){
oBtnNew=document.getElementById("btnNew");
if(window.attachEvent){
oBtnNew.attachEvent("onclick",hanlder);
oBtnNew.attachEvent("onmouseover",hanlder);
}else{
oBtnNew.addEventListener("click",hanlder,false);
oBtnNew.addEventListener("mouseover",hanlder,false);
}
/*或者采用下面试
oBtnNew.onclick=hanlder;
oBtnNew.onmouseover=hanlder;*/
}
function hanlder(event){
event=event?event:window.event;
if(event.type=="click")
oBtnNew.innerHTML="发生了onclick事件";
else if(event.type=="mouseover")
oBtnNew.innerHTML="发生了onmouseover事件";
}
//–>
</script>
</head>
<body>
<button id="btn" onclick="Click(event)">点击</button>
<button id="btnNew">添加事件点击</button>