jQuery's One - Fire once with multiple event types

前端 未结 5 2067
挽巷
挽巷 2020-12-06 12:00

Is there a way to fire a single function once when any event is raised?

For example, if I have the following function: (demo in jsfiddle)



        
5条回答
  •  猫巷女王i
    2020-12-06 12:29

    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/

提交回复
热议问题