I want to attach a click event handler to each and every (Button, Anchor, Select) on all pages in my application, and that handler should run before the already attached handlers declared in html like onclick="return SomeFunction('a','b');"
.
I found a question on stackoverflow for prepending handlers, and that was what I wanted exactly, the link to the question is:-
Jquery prepend click handler
But, the above code is not working, I doubt if it worked for the asker or not. The code I have written according to my requirements is:-
<input type="button" value="Click 1" onclick="f2();" />
$(document).ready(function() {
$("input[type=button]").each(function() {
// your button
var btn = $(this);
// original click handler
var clickhandler = btn.attr("onclick");
btn.attr("onclick", "return false;");
// new click handler
btn.click(function() {
alert('Prepended Handler');
clickhandler();
});
});
});
function f2() {
alert('Handler declared in HTML');
}
The output for this code should have been: An alert showing "Prepended Handler" and then a next alert showing "Handler declared in HTML".
But, the actual result is: Only the first alert is appearing and the second one is not.
Please tell me if you see any problem in this code.
And, how can this be done. ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…