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

Joh*_*ith 13 jquery bind unbind

在2周前在这里问了同样的问题之后,我终于找到了"解决方案".这就是我回答自己问题的原因.;)

如何在JQUERY中绑定,组合和重新绑定事件?

Joh*_*ith 12

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

$(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');
    }
);
Run Code Online (Sandbox Code Playgroud)

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

文档!

这是一个尝试它并试验它的小提琴!

请享用!

  • 重要!对于任何对此感兴趣的人,`.toggle()`方法在jQuery 1.8中已被弃用,而在jQuery 1.9中已被删除。([来源-jQuery.com](https://api.jquery.com/toggle-event/)) (2认同)