问题
I have an anchor like this
<a href='#' onclick='return showform(this)'>click me</a>
But I want to be able to override the onclick function, how to do this in jquery?
because it seems when I add
$('a').click( function() { alert('hi there!'); } );
the new click handler is not overriding the old one
回答1:
Have you tried something like this:
$("a").removeAttr("onclick");
回答2:
In your case the onCick event is overriding the jQuery one. What you might be able to do is:
$('a').unbind('click').click(function(){
alert('why hello there children.');
})
But I believe this would have to be included after the
<a href='#' onclick='return showform(this)'>click me</a>
That said, you should really not be using onClicks anyway... it makes the code really hard to maintain and change (as you have found out).
回答3:
If you're using jQuery like this, you don't want any handlers in the HTML. Can't you just remove the onClick attribute?
If you're worried about breaking stuff, search and replace on:
onclick='return showform(this)'
and replace with
class='showform'
Then you can do:
$('a.showform').click(function (e) {
e.preventDefault();
return showform(this);
});
which will keep your existing handlers working.
回答4:
There is a plugin for it, but you should only do this when you really need to. The plugin allows you to call the original function or ignore/replace it entirely
jQuery Override Plugin
$(divElementObj).override('onclick', 'click', function(...));
来源:https://stackoverflow.com/questions/1927845/jquery-override-event