javascript 如何覆盖先前设置的 jquery 事件处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14063564/
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-10-26 20:37:24  来源:igfitidea点击:

How to override a previously set jquery event handler?

javascriptjqueryevent-handling

提问by Click Upvote

In my code, an event handler for an element is set which changes that element's css height to 100px. At somewhere else, I want a different event handler to be run if certain conditions meet, which should override the previous event handler and change its height to 200px.

在我的代码中,设置了一个元素的事件处理程序,将该元素的 css 高度更改为 100px。在其他地方,如果满足某些条件,我希望运行不同的事件处理程序,它应该覆盖之前的事件处理程序并将其高度更改为 200px。

Is there a way to do that, or to clear all previously set event handlers for an element?

有没有办法做到这一点,或者清除所有先前为元素设置的事件处理程序?

回答by zerkms

Yes, just use .off(), like

是的,只需使用.off(),就像

$('selector').off('eventname')

回答by jfriend00

This is a bit of a hack, but it sounds like you're trying to hack on someone else's code without the ability to change it directly so that may be what you have to resort to.

这有点像黑客攻击,但听起来您正在尝试破解其他人的代码,而无法直接更改它,因此这可能是您必须求助的方法。

If you just need to call something after their document.ready()and you don't control the order of the document.ready()statements, then you can put some code in a short timeout like this inside your document.ready handler:

如果你只需要在它们之后调用一些东西document.ready()并且你不控制document.ready()语句的顺序,那么你可以在你的 document.ready 处理程序中放置一些像这样的短超时代码:

$(document).ready(function() {
    setTimeout(function() {
        $('selector').off('eventname').on(your event handler here);
    }, 1);
});

The setTimeout()will run AFTER all document.ready() handlers have run.

setTimeout()将运行()处理已运行所有的document.ready了。

回答by Alain

Another way:

其他方式:

$(window).on('load', function() {
   $('selector').off('eventname').on(your event handler here);
});

Load is executed after document ready

文件准备好后执行加载