javascript - 使用 jQuery one() 函数作为 hack 来防止触发多个点击事件

标签 javascript jquery onclick jquery-events

我遇到了一个奇怪的问题,即切换按钮的可见性似乎会影响对该按钮调用点击事件的次数。

如果我使用:$('button').on('click'...),只要在点击按钮之前我已经完成,点击按钮只会发生 1 次点击事件整页加载。相反,如果我通过 AJAX 加载包含按钮的页面片段,然后单击按钮,on() 函数会触发多个点击事件,每次我以这种方式加载页面时都会添加一个。

我可以通过使用 $('button').one('click', ... 来限制这些多次点击的触发但是我想知道这是否太 hack-ish 并且它最好首先修复导致多次点击事件触发的原因。

在切换可见性之前是否遇到过此问题 -/+ AJAX 页面加载会影响在点击处理程序上触发多少点击事件?

最佳答案

我猜它根本不是 hack-ish 因为 jQuery Docs for One() 的第一行描述此功能的设计目的。

Attach a handler to an event for the elements. The handler is executed at most once per element.

这很容易说明它可以防止多次引发事件。

这个函数的内部工作原理也和@mgraph提到的一样,在文档中提到:

The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation. The second two forms, introduced in jQuery 1.7, are identical to .on() except that the handler is removed after the first time the event occurs at the delegated element, whether the selector matched anything or not.

更详细一点-

这个方法正常binds an event使用 .bind()/.on() 到处理程序,一旦事件发生一次且仅一次,它 unbinds the event使用 .unbind()/.off()

关于javascript - 使用 jQuery one() 函数作为 hack 来防止触发多个点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10367112/

相关文章:

javascript - 如何在不影响父元素的情况下为子元素设置不同的 onClick 事件?

javascript - 将 javascript 按钮更改为在任何地方单击

javascript - JS 自动转换括号中的文本与特定标记(包括匹配)

javascript - Node.js mssql 返回记录集

javascript - 更改 "caption"在此 jQuery 图像幻灯片上的动画方式

jquery - 如何防止每次单击按钮时 $.getJSON 都会增加?

javascript - HTML - PHP 中的 'onclick' 确认函数

javascript - 在 Play 框架模板中使用 Scala List 填充 Javascript 数组

javascript - 计数元素之间的语法混淆

javascript - JavaScript/jQuery 中的安全 Twitter OAuth 身份验证(加上服务器端助手)