首先参考:javascript attachEvent和addEventListener 使用方法
attachEvent方法,为某一事件附加其它的处理事件。(不支持Mozilla系列)
addEventListener方法 用于 Mozilla系列
举例:
document.getElementById("btn").onclick = method1;
document.getElementById("btn").onclick = method2;
document.getElementById("btn").onclick = method3;
如果这样写,那么将会只有medhot3被执行
写成这样:
var btn1Obj = document.getElementById("btn1");
//object.attachEvent(event,function);
btn1Obj.attachEvent("onclick",method1);
btn1Obj.attachEvent("onclick",method2);
btn1Obj.attachEvent("onclick",method3);
执行顺序为method3->method2->method1
如果是Mozilla系列,并不支持该方法,需要用到addEventListener
var btn1Obj = document.getElementById("btn1");
//element.addEventListener(type,listener,useCapture);
btn1Obj.addEventListener("click",method1,false);
btn1Obj.addEventListener("click",method2,false);
btn1Obj.addEventListener("click",method3,false);
执行顺序为method1->method2->method3
var newopen = function(id,level)
{
return function()
{
opentree(id,level);//该函数为外部定义的一个执行函数;
}
}
x.attachEvent("onclick",newopen(id,parseInt(level)+1));
y.attachEvent("onclick",newopen(id,parseInt(level)+2));
think8848的简化代码:
if ( x.addEventListener) //如果浏览器为Firefox
{
x.addEventListener("click",function()
{
opentree(id,level); //opentree为外部定义的一个执行函数,id,level为实参;
});
}
else //浏览器为IE
{
x.attachEvent("onclick",function()
{
opentree(id,level);
});
}
方法二:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body>
<a href="#" id="mylink">这是连接</a>
<script type="text/javascript">
function AttachEvent(type, target, handler, owner)
{
var eventHandler = handler;
if(owner)
{
debugger;
// 在这里重新定义一个处理函数
eventHander = function(e)
{
handler.call(owner, e);
}
}
if(window.document.all)
target.attachEvent("on" + type, eventHander );
else
target.addEventListener(type, eventHander, false);
}
function MyLink_Click(e)
{
alert(this.tagName);
var target = e.srcElement || e.target;
alert(target.href);
}
function test()
{
var mylink = window.document.getElementById("mylink");
AttachEvent("click", mylink, MyLink_Click, mylink);
}
</script>
<input type="button" value="AttachEvent" onclick="test()" />
</body>
</html>