JavaScript dynamically changes the onclick event

Source: Internet
Author: User

The first type: Button.onclick = Function ("alert (' Hello ');");

The second type: Button.onclick = function() {alert ("Hello");};

The Third Kind: Button.onclick = Myalert;

function Myalert () {
Alert ("Hello");
}

The fourth type:

This situation is more dynamic, more practical, and can add multiple functions (the order in which the events are added is the order of execution), hehe
    if (window.addeventlistener) {//Mozilla , Netscape, Firefox
        //element.addeventlistener (Type,listener, Usecapture);
        button.addeventlistener (' Click ', alert (' One '), false);
        button.addeventlistener (' Click ', alert (' n '), false);// Execution order
    } else {//IE
         Button.attachevent (' onclick ', function () {alert (' 21 ');});
        button.attachevent (' onclick ', function () {alert (' 22 ');}); Execution order
    }

Example Explanation:
Button.onclick = Function ("alert (' 31 ');");
Button.onclick = Function ("alert (' 32 ');");
Button.onclick = Function ("alert (' 33 ');"); If this is the case, then only the last method will be executed.

Button.attachevent ("onclick", function () {alert (' 41 ');});
Button.attachevent ("onclick", function () {alert (' 42 ');});
Button.attachevent ("onclick", function () {alert (' 43 ');}); If this is the case, three methods will be executed.

Of course, you can write that too.
Button.onclick = Function ("alert (' 51 ');");
Button.attachevent ("onclick", function () {alert (' 52 ');});

Corresponding removal events
DetachEvent (' onclick ', func);//ie using Delete event func
RemoveEventListener (' click ', func);//mozilla, delete event func

JavaScript dynamically changes the onclick event

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.