Add events dynamically in Javascript

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.