jquery removes button's inline onclick event (tested and compatible browsers) _jquery

Source: Internet
Author: User

The inline onclick code is as follows :

Copy Code code as follows:

<input type= "button" id= "Btnok" name= "" value= "to determine" onclick= "Btnokclick ();"/>

Btnokclick's Code
Copy Code code as follows:

function Btnokclick () {
Alert ("Btnok clicked");
}

Now, after clicking the button, remove the onclick event and bind a new click event for the button. At the second click, the second event handler is executed, and the second handler is the code for the function:
Reclick's Code
Copy Code code as follows:

function Reclick () {
Alert (' Reclick ');
}
[\s\s]*\n

train of Thought: Remove the onclick in Btnokclick and add a new binding with the following code:
Copy Code code as follows:

$ (' #btnOK '). attr (' onclick ', '). Bind (' click ', Function () {Reclick ();});

The Btnokclick method after adding this code is as follows:
Copy Code code as follows:

function Btnokclick () {
Alert ("Btnok clicked");
$ (' #btnOK '). attr (' onclick ', '). Bind (' click ', Function () {Reclick ();});
}

This method works well under Google Chrome, but in IE's compatibility mode it will call the Reclick method immediately, which is not the effect we want.

The reason for this effect seems to be that after the onclick execution, ie go back to see if there is a binding on the click of the handler, the structure is there, so immediately executed.

In order to solve this problem, we can change the idea, that is, delay binding click event. The specific code is as follows:
Copy Code code as follows:

function Btnokclick () {
Alert ("Btnok clicked");
settimeout (function () {
$ (' #btnOK '). attr (' onclick ', '). Bind (' click ', Function () {Reclick ();});
}, 1);
}

Here the settimeout timer is used, and after the timer is triggered, the OnClick property is removed and the code that binds click handler is executed.
After testing, in IE9 compatibility mode and incompatible mode can operate normally; Google Chrome also works.

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.