jQuery的One - 一次有多种事件类型 [英] jQuery's One - Fire once with multiple event types
问题描述
根据 一个
的文档:
如果第一个参数包含多个空格分隔事件类型,则事件处理程序对于每个事件类型称为一次
有什么方法可以在任何事件发生时触发单个功能一次?
示例:
$('input' ('mouseup keyup',function(e){
console.log(e.type);
});
我只想调用函数一次,不管哪个事件触发了。 >
目前该功能将针对每个事件类型触发一次。
小提琴演示
注意:我不是在这里寻找
焦点
事件...这只是一个例子。
而不是使用 .one
,请使用 .on
,并使用 <$ c $手动删除绑定c> .off 。
$('input')。on mouseup keyup',function(e){
console.log(e.type);
$(this).off('mouseup keyup');
});
小提琴: http://jsfiddle.net/23H7J/3/
这可以使用命名空间做一点更加优雅:
$('input')。on('mouseup.foo keyup.foo' ,function(e){
console.log(e.type);
$(this).off('。foo');
});
这允许我们使用单个标识符(foo)来删除任何数量的绑定,我们赢了不要影响元素可能存在的任何其他鼠标或键盘绑定。
小提琴: http://jsfiddle.net/23H7J/41/
According to the docs for one
:
If the first argument contains more than one space-separated event types, the event handler is called once for each event type.
Is there a way to fire a single function once when any event is raised?
Example:
$('input').one('mouseup keyup', function(e){
console.log(e.type);
});
I'd like to only call the function once, regardless of which event fired it.
Currently the function will fire once for each event type.
Demo in Fiddle
Note: I'm not looking for the
focus
event here... this is just an example.
Instead of using .one
, use .on
and remove the binding manually with .off
.
$('input').on('mouseup keyup', function(e){
console.log(e.type);
$(this).off('mouseup keyup');
});
Fiddle: http://jsfiddle.net/23H7J/3/
This can be done a little more elegantly with namespaces:
$('input').on('mouseup.foo keyup.foo', function(e){
console.log(e.type);
$(this).off('.foo');
});
This allows us to use a single identifier (foo) to remove any number of bindings, and we won't affect any other mouseup or keyup bindings the element may have.
Fiddle: http://jsfiddle.net/23H7J/41/
这篇关于jQuery的One - 一次有多种事件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!