Four Methods for registering and removing events in javascript

Source: Internet
Author: User

There are many ways to register events for some elements in html.
First:
Copy codeThe Code is as follows:
<Script>
Function test ()
{
Alert ("OK ");
}
</Script>
<A href = "#" onclick = "test ()"> test </a>

Second:
Copy codeThe Code is as follows:
<A href = "#" id = "a"> test </a>
<Script>
Function test ()
{
Alert ("OK ");
}
Var x = document. getElementById ("");
X. onclick = test; // note that no ()
</Script>

Third (W3C model ):
Copy codeThe Code is as follows:
<A href = "#" id = "a"> test </a>
<Script>
Function test ()
{
Alert ("OK ");
}
Var x = document. getElementById ("");
X. addEventListener ("click", test, false );
</Script>

Among the three parameters, addEventListener (), the first indicates the event type, note that there is no on, the second specifies the method, and the third indicates event bubbling (true) or event capture (false), which involves the sequence of events from bottom to top or from top to bottom.
RemoveEventListener () is used to remove an event. The parameter is the same as addEventListener.
In this mode, an error is reported in IE browser, which is executed normally in chrome.

Fourth (Microsoft model ):
Copy codeThe Code is as follows:
<A href = "#" id = "a"> test </a>
<Script>
Function test ()
{
Alert ("OK ");
}
Var x = document. getElementById ("");
X. attachEvent ("onclick", test );
</Script>

Among the two parameters, attachEvent () indicates the first event type, with on and the second method.
The method for removing an event is detachEvent (). The parameter is the same as that of attachEvent.

Related Article

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.