jQuery事件处理程序仅在将绑定到多个元素后才执行 [英] jquery event handler to execute only once the is bound to multiple elements
问题描述
我想要一个仅执行一次的事件处理程序,然后将其自身与绑定到的所有元素解除绑定.
I want to have an event handler that executes only once and then unbinds itself from all the elements it was bound to.
我知道.one()
,但是使用它时,该处理程序最多每个元素执行一次".
I know of .one()
but when using it "The handler is executed at most once per element".
是否有一种内置"方式将事件处理程序绑定到多个元素,并且一旦在其中任何一个元素上执行该事件处理程序,就会自动将其从所有元素中删除?
Is there a "built-in" way to bind an event handler to multiple elements and have it removed automatically from all of the once it is executed on any one of them?
推荐答案
简单.只需将事件处理程序绑定到回调函数中即可.像这样:
Easy. Just unbind the event handler inside the callback function. Like this:
$('p').on('click', function(){
alert('I appear only one time');
$('p').off('click'); // Removes the event. So, it will never be executed again.
})
此脚本将删除所有 click 类型的事件,这有点让人讨厌.检查文档中的 关闭 和
This script will remove all events of type click, and that is a bit aggresive. Check the documentation for off and unbind for more info.
这篇关于jQuery事件处理程序仅在将绑定到多个元素后才执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!