jQuery unbind click事件不起作用

时间:2013-11-25 12:14:51

标签: jquery unbind

如果我的链接有“rebind”类,我想在按钮上禁用单击事件。 我试过这种方式(jsFiddle:http://jsfiddle.net/D6Qh5/):

$('#button').bind('click', function(){
    $(this).after('<span> click is active</span>');
    $('span').fadeOut(1000);
});

$('#toggle').toggle(
    function(){
        $(this).text('rebind').removeClass('unbind').addClass('rebind');
    },
    function(){

     $(this).text('unbind').addClass('unbind').removeClass('rebind');
    }
);

if($("#toggle").hasClass("unbind")) {
    $('#button').bind('click');
}
else {
    $('#button').unbind('click');
}

但是 unbind 不起作用,我在Firebug上没有任何错误。我不知道我做错了什么 任何帮助表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:2)

你的bind,unbind方法放错了地方。

$('#button').on('click', Button_Click);

function Button_Click(){
    $(this).after('<span> click is active</span>');
    $('span').fadeOut(1000);
}

$('#toggle').toggle(
    function(){
        $(this).text('rebind').removeClass('unbind').addClass('rebind');
            $('#button').unbind('click');

    },
    function(){

     $(this).text('unbind').addClass('unbind').removeClass('rebind');
            $('#button').bind('click',Button_Click);
    }
);

http://jsfiddle.net/FtATg/
同样在jQuery 1.7中,.on()和.off()方法更适合在元素上附加和删除事件处理程序。

相关问题