本文介绍如何在运行时为元素添加事件以及添加带参数引用。我们在此通过attachEvent以及addEventListener
来为指定元素动态添加事件。其中,IE浏览器以及使用IE内核的浏览器中使用方法(attachEvent)来为元素动态添加
处理事件。其他浏览器则使用(addEventListener)方法动态添加处理事件。
以下是示例代码:


/*
*功能:返回ID为elid的元素
*参数:
* elid:元素标识
*/
function $(elid){return typeof(elid)=="string"?document.getElementById(elid):elid;}
/*
*功能:为目标元素添加相应处理事件
*参数:
* strElment:目标Element标识
* oEvent:事件
* ofunc:处理函数
*/
function $Event(strElment,oEvent,ofunc){
//依据不同浏览器,使用不同方法。
if(window.addEventListener)
$(strElment).addEventListener(oEvent,ofunc,false);
else
$(strElment).attachEvent("on"+oEvent,ofunc);
}
var elID=new Array("tmtd$tmpmgt","nltd$nltmgt");
function InitMenu()
{
for(i=0;i<elID.length;i++)
{
elst=elID[i].split("$");
$Event(elst[0],"mouseover",shfunction(elst[1],true));
$Event(elst[0],"mouseout",shfunction(elst[1],false));
$Event(elst[1],"mouseover",shfunction(elst[1],true));
$Event(elst[1],"mouseout",shfunction(elst[1],false));
}
}
//使用闭包为事件处理函数传递参数
var shfunction=function(strEl,bshow)
{
return function()
{
for(i=0;i<elID.length;i++)
{
elst=elID[i].split("$");
$(elst[1]).className="hid";
}
$(strEl).className=bshow?"show":"hid";
}
}
以下是支持代码:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
