jquery 覆盖事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1927845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:25:40  来源:igfitidea点击:

jquery override event

jqueryoverriding

提问by strike_ntheitroad

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?

但我希望能够覆盖 onclick 函数,如何在 jquery 中做到这一点?

because it seems when I add

因为当我添加时似乎

$('a').click( function() { alert('hi there!'); } );

the new click handler is not overriding the old one

新的点击处理程序不会覆盖旧的点击处理程序

回答by SeanJA

In your case the onCick event is overriding the jQuery one. What you might be able to do is:

在您的情况下, onCick 事件覆盖了 jQuery 事件。你可能能够做的是:

$('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).

也就是说,无论如何你真的不应该使用 onClicks ......它使得代码很难维护和更改(正如你所发现的)。

回答by kgiannakakis

Have you tried something like this:

你有没有尝试过这样的事情:

$("a").removeAttr("onclick");

回答by Skilldrick

If you're using jQuery like this, you don't want any handlers in the HTML. Can't you just remove the onClickattribute?

如果您像这样使用 jQuery,则您不需要 HTML 中的任何处理程序。你不能删除onClick属性吗?

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.

这将使您现有的处理程序保持工作。

回答by aikeru

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

jQuery 覆盖插件

$(divElementObj).override('onclick', 'click', function(...));