Home > Web Front-end > JS Tutorial > jquery removes the inline onclick event of the button (tested and compatible with browsers)_jquery

jquery removes the inline onclick event of the button (tested and compatible with browsers)_jquery

WBOY
Release: 2016-05-16 17:42:49
Original
1102 people have browsed it

The inline onclick code is as follows:

Copy code The code is as follows:



btnOKClick code :
Copy code The code is as follows:

function btnOKClick() {
alert("btnOK Clicked");
}

Now after clicking the button, remove the onclick event and bind a new click event to the button. On the second click, the second event processing function starts to be executed. The code of the second processing function:
reclick code:
Copy code The code is as follows:

function reclick() {
alert('reclick');
}
[sS ]*n

Idea: Remove onclick in btnOKClick, and then add a new binding, the code is as follows:
Copy code The code is as follows:

$('#btnOK').attr('onclick', '').bind('click', function () { reclick(); });

The btnOKClick method after adding this code is as follows:
Copy code The code is as follows:

function btnOKClick() {
alert("btnOK Clicked");
$('#btnOK').attr('onclick' , '').bind('click', function () { reclick(); });
}

This method works normally under Google Chrome, but is not compatible with IE The reclick method will be called immediately in mode, which is not the effect we want.

The reason for this effect seems to be that after onclick is executed, IE goes back to check whether there is a handler bound to click. The structure is there, so it is executed immediately.

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

function btnOKClick() {
alert("btnOK Clicked");
setTimeout(function () {
$('#btnOK').attr('onclick', '').bind('click', function () { reclick (); });
}, 1);
}

The setTimeout timer is used here. After the timer is triggered, the onclick attribute is removed and click is bound. handler code.
After testing, it can run normally in both the compatibility mode and non-compatibility mode of IE9; Google Chrome also runs normally.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template