如何在 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
How to bind, unbind and rebind (click) events in JQuery
提问by John Doe Smith
采纳答案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');
});