JS four ways to modify the onclick action __js

Source: Internet
Author: User

First: Button.onclick = Function ("alert (' Hello ');");

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

The third type: Button.onclick = Myalert;

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

The fourth kind:

This situation is more dynamic, more practical, but also can add more than one function (add the sequence of events 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 ('), false);//execution Order-> 12
else {//IE
Button.attachevent (' onclick ', function () {alert (' 21 ');});
Button.attachevent (' onclick ', function () {alert (' 22 ');}); Order of Execution-> 21
}

Example Explanation:
Button.onclick = Function ("alert (' 31 ');");
Button.onclick = Function ("alert (' 32 ');");
Button.onclick = Function ("alert (' 33 ');"); If you write this, 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 you write this, three methods will be executed

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

Corresponds to the removal event
DetachEvent (' onclick ', func);//ie using Delete event func
RemoveEventListener (' click ', func);//mozilla, delete event func

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.