JavaScript event handlers execution order

后端 未结 2 1082
臣服心动
臣服心动 2021-01-18 05:29

Having this JS code:

document.getElementById(\'e1\').addEventListener(\'click\', function(){alert(\'1\');}, false);
document.getElementById(\'e2\').addEventL         


        
相关标签:
2条回答
  • 2021-01-18 05:39

    I will be 1 and then 2 . http://jsfiddle.net/kkYfX/

    0 讨论(0)
  • 2021-01-18 05:57

    The alerts will be executed in order - 1 and then 2. This is because click event is synchronous (see here) - when .click() is issued the handler will be run immediately (look at the last paragraph here). So this code:

    document.getElementById('e1').addEventListener('click', function(){alert('1');}, false);
    document.getElementById('e2').addEventListener('click', function(){alert('2');}, false);
    document.getElementById('e1').click();
    document.getElementById('e2').click();
    alert('3');
    

    will produce the same result as

    alert('1');
    alert('2');
    alert('3');
    
    0 讨论(0)
提交回复
热议问题