The current page layout is based on XHTML. DHTML styles are implemented through Div + CSS layout. Therefore, this JavaScript dynamically adds events to elements, so it is common. Next I will talk about how to dynamically add events for elements through JavaScript.
Javascript dynamically adds events to elements in two cases:
Events without parameters and events with parameters.
1. events without parameters:
Two Methods: directly add events to objects and add events to nodes
For example, to add an onclick event whose ID is tab1
First case:
VaR T = Document. getelementbyid ("newtitle ");
T. onclick = function showmsg (){
Alert ('Hello! World ');
}
The second case is more dynamic and practical. You can also add multiple functions (the order of the added events is the execution order ).
VaR TB = Document. getelementbyid ("newtitle ");
If (window. addeventlistener) {// Mozilla, Netscape, Firefox
Td_value.addeventlistener ('click', alert ('cc'), false );
Td_value.addeventlistener ('click', alert ('cc'), false );
} Else {// IE
Td_value.attachevent ('onclick', function () {alert ('changchange ');});
Td_value.attachevent ('onclick', function () {alert ('changchange ');});
}
2. events with Parameters
The functionname here is the event processing function. What should I do if it contains parameters,
Some people say this:
Element. onclick = function (SB ){
Alert (SB );
}
Is it the method above? The answer is incorrect.
Solution: anonymous functions:
Element. onclick = function (){
Functionname (PARAM );
};
In this way, it is achieved through the anonymous method!
Make the best effort and pursue the highest achievement.