在jQuery中,有没有办法只绑定一次点击? [英] In jQuery, is there any way to only bind a click once?

查看:525
本文介绍了在jQuery中,有没有办法只绑定一次点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ajax应用程序,可以在每次交互时运行函数。我希望每次都能运行我的设置功能,所以我的所有设置代码都保持封装状态。但是,绑定元素不止一次意味着处理程序将运行多次,这显然是不可取的。在jQuery中是否有一种优雅的方法可以在不多次调用处理程序的情况下多次调用一个元素上的绑定?

I have an ajax app that will run functions on every interaction. I'd like to be able to run my setup function each time so all my setup code for that function remains encapsulated. However, binding elements more than once means that the handler will run more than once, which is obviously undesirable. Is there an elegant way in jQuery to call bind on an element more than once without the handler being called more than once?

推荐答案

您可以使用 one()函数将事件附加到文档

You could attach the event to document with the one() function:

$(document).one('click', function(e) {
    // initialization here
});

一旦运行,此事件处理程序将再次被删除,以便它不会再次运行。但是,如果您需要初始化以在之前运行某个其他元素的click事件,我们将不得不考虑其他内容。然后使用 mousedown 而不是点击,因为在点击事件之前触发了mousedown事件。

Once run, this event handler is removed again so that it will not run again. However, if you need the initialization to run before the click event of some other element, we will have to think of something else. Using mousedown instead of click might work then, as the mousedown event is fired before the click event.

这篇关于在jQuery中,有没有办法只绑定一次点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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