有没有办法在引发任何事件时触发一次单个函数?
例如,如果我有以下函数:( demo in jsfiddle )
$('input').one('mouseup keyup', function(e){
console.log(e.type);
});
我只想调用该函数一次,而不管哪个事件触发了它。
但是根据docs对于 .one()
:
If the first argument contains more than one space-separated event types, the event handler is called once for each event type.
因此,目前该函数将为每种事件类型触发一次。
最佳答案
而不是使用 .one
, 使用 .on
并使用 .off
手动删除绑定(bind).
$('input').on('mouseup keyup', function(e){
console.log(e.type);
$(this).off('mouseup keyup');
});
fiddle :http://jsfiddle.net/23H7J/3/
这可以通过命名空间更优雅地完成:
$('input').on('mouseup.foo keyup.foo', function(e){
console.log(e.type);
$(this).off('.foo');
});
这允许我们使用单个标识符 (foo) 来删除任意数量的绑定(bind),并且我们不会影响元素可能具有的任何其他 mouseup 或 keyup 绑定(bind)。
fiddle :http://jsfiddle.net/23H7J/41/
关于javascript - jQuery 的一个——使用多种事件类型触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589084/