jQuery's One - Fire once with multiple event types

前端 未结 5 2073
挽巷
挽巷 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条回答
  •  醉话见心
    2020-12-06 12:30

    A simpler way to fire once but keep firing on subsequent changes, is to temporarily store the previous value and do a quick comparison: If nothing has changed then don't run the rest of the function.

    jQUERY

    $('input').on('keyup paste input change', function(e){ 
        var oldValue = $(e.target).data('oldvalue');
        var newValue = $(e.target).val();
    
        if (oldValue === newValue) //nothing has changed
            return;
    
        $(e.target).data('oldvalue',newValue); //store the newly updated value
    
        //proceed with the rest of the function
    });
    

    Note that I'm using .on to attach the events, instead of .one

    PURE JAVASCRIPT

    For a pure JavaScript solution, listeners need to be added separately, since it's not possible to pass multiple events to .addEventListener.

    var selector = document.querySelector('input')
    selector.addEventListener('keyup', updateElement);
    selector.addEventListener('paste', updateElement);
    selector.addEventListener('input', updateElement);
    selector.addEventListener('change', updateElement);
    
    function updateElement(e){
        var oldValue = e.target.getAttribute('oldvalue');
        var newValue = e.target.value;
    
        if (oldValue === newValue) //nothing has changed
           return; 
        console.log (newValue);
        e.target.setAttribute('oldvalue', newValue); //store the newly updated value
    
        //proceed with the rest of the function
    }
    

    Assuming you want to listen for changes in the input box, I suggest not to use mouseup to detect a possible Right click > paste, since the mouse could be released somewhere else, not necessarily inside the input box. To be on the safe side you better use keyup, paste, input and change, as I did on my code above.

提交回复
热议问题