本文介绍了jQuery的One - 一次有多种事件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据的文档:

有什么方法可以在任何事件发生时触发单个功能一次?



示例:

  $('input' ('mouseup keyup',function(e){
console.log(e.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

解决方案

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 - 一次有多种事件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 22:56