jQuery .on(); vs JavaScript .addEventListener();

前端 未结 2 746
孤城傲影
孤城傲影 2020-11-29 22:21

Can someone explain me why is there a difference in the order in which the event handlers are being executed depending on how they have been attached? In the example below I

2条回答
  •  天命终不由人
    2020-11-29 22:56

    Look at the addEventListener version:

    document.getElementById('outer').addEventListener('mouseup', function (event) {
        alert('This alert should not show up!');
    }, false);
    

    That works fine because the third argument is useCapture, which specifies whether or not the capture phase of the event should be used.

    When you switch to the jQuery version:

    $('#outer').on('mouseup', function (event) {
        alert('This alert should not show up!');
    }, false);
    

    I think what is happening is the third argument simply overrides your event handler function and causes the event handler to do nothing but return false; which is clearly not what is meant to happen.

    From the jQuery docs (emphasis added):

    A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.

    Remove the false argument and the jQuery version will work correctly too:

    $('#outer').on('mouseup', function (event) {
        alert('This alert should not show up!');
    });
    

    Note that the alert should show up, so the addEventListener approach is working correctly. See @Pointy's answer for why that is.

提交回复
热议问题