jQuery event triggers twice

后端 未结 3 637
不知归路
不知归路 2021-02-11 04:11

Can someone explain to me why this event triggers twice? It doesn\'t seem to do it on jQuery versions prior to 1.7.



        
相关标签:
3条回答
  • 2021-02-11 04:25

    From the internals, it looks like triggering blur event is triggering blur and focusout events internally which is invoking the onblur twice.

    PoC

    $('#box').on('blur focusout', function (e) {
        console.log('this too', e.type);
    });
    $('#box').blur();
    

    Demo: Fiddle

    The blur event is a non bubbling event, the bubbling counterpart is the foucsout event. So in normal circumstances the blur operation triggers both these events. So jQuery is trying to be intelligent and fires both these events in case of a blur event, but it looks like there is an bug in the implementation.

    0 讨论(0)
  • 2021-02-11 04:31

    You just need to call it once:

    $('#box').on('blur', function() {
        console.log('This will trigger twice!');
    });
    
    $('#box').blur();
    

    Updated Fiddle

    or just remove your jQuery code and keep your onblur event inside your input tag.

    0 讨论(0)
  • 2021-02-11 04:40

    Edit: This might be a solution to your problem.

    JSFIDDLE http://jsfiddle.net/SvqwF/7/

    Based on focusout.


    You trigger it twice, because the .blur() is trigger to

    .on('blur focusout', function(){}) (Thanks to @Arun P Johny)
    

    which just triggers the event listener you added inline also, if you do not pass a function to .blur(). JSFIDDLE

    Since you added a function inline, that function gets triggered twice.

    Description: Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. jQuery .blur()

    To get more about the method (for old IE .attachEvent) that is involved with jQuery:

    To register more than one event listener for the target, call addEventListener() for the same target but with different event types or capture parameters. MDN

    Note: I am unsure as to which event to declare in .on(), it seems like all work

    The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser "focusin" and "focusout" events that do bubble. When "focus" and "blur" are used to attach delegated event handlers, jQuery maps the names and delivers them as "focusin" and "focusout" respectively. jQuery .on()

    Note 2: blur() <- empty is a shortcut for trigger('blur'). JSFIDDLE

    0 讨论(0)
提交回复
热议问题