The usage of JS native attachevent and AddEventListener

Source: Internet
Author: User

Now jquery is more popular, so we use more is jquery, rarely with the native JS. But still need to understand the drop.

The code is as follows:

<a id= "Btnclick" href= "javascript:void (0);" > Click me </a>

If we're going to bind three functions to the button's Click button, it's easier for a person with less knowledge of JS to write this:

<script type="text/javascript">var ele=document.getelementbyid ("  test"); Ele.click=Method1;ele.click=Method2;ele.click=  method3; </script>

This is wrong because the click event will only execute function 3. So we need to use the attachevent and AddEventListener events, attachevent only for IE browser, and AddEventListener only for Firefox

Browser. The correct wording is as follows:

<script type="Text/javascript">varEle=document.getelementbyid ("Test");if(window.attachevent) {ele.attachevent ("onclick", function () {alert ("you clicked on me.");}) Ele.attachevent ("onclick", function () {alert ("you hit me again.");}) Ele.attachevent ("onclick", function () {alert ("And you hit me again.");})}Else{Ele.addeventlistener ("Click", function () {alert ("you clicked on me.");}) Ele.addeventlistener ("Click", function () {alert ("you hit me again.");}) Ele.addeventlistener ("Click", function () {alert ("And you hit me again.");})}</script>

Careful people will find that using attachevent when we use the onclick, with AddEventListener when using the click.

At the same time, the functions used to remove the binding are Deattachevent and RemoveEventListener respectively.

The usage of JS native attachevent and AddEventListener

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.