jquery 点击处理程序多次触发
我的 saveBtn 单击事件多次触发时遇到问题,因为每次用户调用该函数时都会调用下面的函数并注册一个新的单击处理程序。如何只注册一键事件处理程序?
function forceAnnotation(annotationNo,objectNo,clientNo, callBack) {
$('#forcedAnnotation').dialog( {
modal: true,
width: 385,
height: 370,
closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
});
$('#cancelBtn').click(function() {
callBack.onCancel();
$('#forcedAnnotation').dialog("close")
});
$('#saveBtn').click(function(){
//make ajax call
});
}
Im having trouble that my saveBtn click events fire multipli times because the function below is called and registering a new click handler for each time the user calls the function. How do i only register one click event handler?
function forceAnnotation(annotationNo,objectNo,clientNo, callBack) {
$('#forcedAnnotation').dialog( {
modal: true,
width: 385,
height: 370,
closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
});
$('#cancelBtn').click(function() {
callBack.onCancel();
$('#forcedAnnotation').dialog("close")
});
$('#saveBtn').click(function(){
//make ajax call
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许你可以使用 jQuery.one() 函数。
“将处理程序附加到元素的事件。每个元素最多执行一次处理程序。”
http://api.jquery.com/one/
Maybe you could use the jQuery.one() function.
"Attach a handler to an event for the elements. The handler is executed at most once per element."
http://api.jquery.com/one/
如果您每次都被迫添加单击处理程序,为什么不每次都将其分离:
为了确保您只是取消绑定此特定的单击处理程序,您可以使用命名空间。
这应该有效,我希望
If you are forced to add the click handler every time why not just detach it every time also with:
To make sure you just unbind this specific click handler you can use namespaces.
This should work, I hope
最简单的方法是重构代码,将
click
处理程序注册删除到函数之外。如果这是不可能的,您可以在
forceAnnotation()
函数的范围之外声明取消函数。并在您的函数中将其重新定义为您所需要的。其他选项是
.one()
或者每次都简单地
unbind()
点击处理程序。The easiest way would be to refactor your code to remove the
click
handler registration to be outside of the function.If that is not possible, you could declare the cancel function outside of the scope of your
forceAnnotation()
function. And in your function redefine it to be what you need.Other options are,
.one()
Or to simply
unbind()
the click handler each time.