jquery防止重复分配的功能 [英] jquery prevent duplicate function assigned

查看:148
本文介绍了jquery防止重复分配的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要动态分配点击功能,有没有办法确保点击功能只能分配一次而不是重复?

If I need to assign a click function dynamically, is there a way to ensure the click function is only assigned once and not duplicated?

this.click(function(){
    alert('test');
})


推荐答案

您可以在绑定该事件之前解除绑定,这样只能附加一个事件:

You can unbind the click event before you bind it again, that way you will only have one event attached to it:

//assuming this is a jquery object.
this.unbind("click");
this.click(function(){
  alert("clicked once");
});

截至jQuery 1.7,现在点击使用.on( http://api.jquery.com/click/ ),所以正确的代码现在是

As of jQuery 1.7, click now uses .on (http://api.jquery.com/click/) so the correct code is now

//assuming this is a jquery object.
this.off("click");
this.click(function(){
  alert("clicked once");
});

这将取消绑定所有点击事件(包括您可能使用的任何插件创建的)。为了确保您仅使用命名空间解除事件绑定。 ( http://api.jquery.com/off/

This will unbind all click events (including ones created by any plugins you might be using). To make sure you only unbind your event use namespaces. (http://api.jquery.com/off/)

//assuming this is a jquery object.
this.off("click.myApp");
this.on("click.myApp", function(){
  alert("clicked once");
});

这里myApp是命名空间。

Here myApp is the namespace.

这篇关于jquery防止重复分配的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆