如何在 JQuery 中绑定、解除绑定和重新绑定(单击)事件

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

How to bind, unbind and rebind (click) events in JQuery

jquerybindunbind

提问by John Doe Smith

After asking the same question 2 weeks ago here, I finally found "the" solution. This is why I am answering my own question. ;)

两周前在这里问了同样的问题后,我终于找到了“the”解决方案。这就是为什么我要回答我自己的问题。;)

HOW TO BIND, UNBIND AND REBIND EVENTS IN JQUERY?

如何在 JQUERY 中绑定、解除绑定和重新绑定事件?

采纳答案by John Doe Smith

And THIS is the perfect solution. (At least for me.)

这是完美的解决方案。(至少对于我来说。)

$(document).on('click', 'a#button', function(){
    $(this).after('<span> hello</span>');
    $('span').fadeOut(1000);
});

$('a#toggle').toggle(
    function(){
        $(this).text('rebind');
        $('a#button').on('click.disabled', false);
    },
    function(){
        $(this).text('unbind');
        $('a#button').off('click.disabled');
    }
);

".on()" does it. NOTE: It is important to bind the event like you can see on line one! It does not work with .click() or …!

“.on()”做到了。注意:像您在第一行看到的那样绑定事件很重要!它不适用于 .click() 或 ...!

See the docs!

查看文档

Here is a fiddleto try it and experiment with it!

这是一个尝试和实验的小提琴

Enjoy!

享受!

回答by Wessam El Mahdy

A simpler and short solution is to add a class to the object if you want to unbind it then remove this class to rebind ex;

一个更简单和简短的解决方案是,如果要解除绑定,则向对象添加一个类,然后删除该类以重新绑定 ex;

$('#button').click( function(){
   if($(this).hasClass('unbinded')) return;
   //Do somthing
 });

$('#toggle').click(function(){
    $('#button').toggleClass('unbinded');
 });