This topic describes how to add an event to an element at runtime and add a reference with parameters. Here we use attachevent and addeventlistener
To dynamically add events to a specified element. Specifically, the IE browser and the method used in the browser using the IE kernel (attachevent) are used to dynamically add elements
Process events. Other browsers use the (addeventlistener) method to dynamically add and process events.
The following is an exampleCode:
Code
/*
* Function: returns the element whose ID is ELID.
* Parameters:
* ELID: Element ID
*/
Function $ (ELID ){ Return Typeof (ELID) = " String " ? Document. getelementbyid (ELID): ELID ;}
/*
* Function: add events for the target element.
* Parameters:
* Strelment: Target element ID
* Oevent: Event
* Ofunc: Processing Function
*/
Function $ Event (strelment, oevent, ofunc ){
// Use different methods based on different browsers.
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 ));
}
}
// Use closures to PASS Parameters for event processing functions
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 " ;
}
}
The following code is supported:
Code
1 < Table Cellpadding = "0" Cellspacing = "0" Style = "Padding: 0px; margin: 0px ;" >
2 < Tr Style = "Background-color: # CCC; padding: 4px ;" >
3 < TD ID = "TMTD" > Template Management </ TD >
4 < TD ID = "Nltd" > Category Management </ TD >
5 </ Tr >
6 < Tr >
7 < TD >
8 < Ul Class = "Hid" ID = "Tmpmgt" >
9 < Li > < A Href = "Tmplist" > Template Management </ A > </ Li >
10 < Li > < A Href = "Edittmp ." > Add Template </ A > </ Li >
11 </ Ul >
12 </ TD >
13 < TD >
14 < Ul Class = "Hid" ID = "Nltmgt" >
15 < Li > < A Href = "Nlttypelist ." > CATEGORY list </ A > </ Li >
16 < Li > < A Href = "Editnlttype ." > Add category </ A > </ Li >
17 </ Ul >
18 </ TD >
19 </ Tr >
20 </ Table >