[转]JavaScript为事件处理器传递参数
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>