onClick priority over addEventListener in javascript?

后端 未结 2 1377
故里飘歌
故里飘歌 2020-12-31 11:50

Right now, I have an event listener that listens to a click on the screen. There is also a button on the screen. When I click on the button the event listener will execute b

相关标签:
2条回答
  • 2020-12-31 12:10

    One solution would be to use inline differently. When .addEventListener need to wait for DOM, on the other hand inline onclick binds while DOM is loading.

    <script>
    document.body.addEventListener('click',function(){alert('1');}, false);
    
    function clicked() { 
        alert('2');
    }
    </script>
    <button onclick="alert('2');">Click this</button>
    

    JSFIDDLE: http://jsfiddle.net/8j9q23jw/

    0 讨论(0)
  • 2020-12-31 12:18

    addEventListner's third argument is the useCapture flag. If you set it to true, handler will be executed while the event is traveling down to the button element. However, if you set it to false, the handler will be triggered while the event is bubbling up:

      capture phase  | |  / \ bubbling up
    -----------------| |--| |-----------------
    | element1       | |  | |                |
    |   -------------| |--| |-----------     |
    |   |element2    \ /  | |          |     |
    |   --------------------------------     |
    |        W3C event model                 |
    ------------------------------------------
    

    From: http://www.quirksmode.org/js/events_order.html#link4

    In your example, the onclick should be executed before the click handler on the body tag. If you want to reverse the order of execution, you should capture the event at body.

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