jquery防止重复的函数分配 [英] jquery prevent duplicate function assigned

查看:105
本文介绍了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');
})

$ b b

推荐答案

您可以在再次绑定点击事件之前解除绑定,这样您只会有一个事件附加到它:

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天全站免登陆