JavaScript event handlers execution order

你说的曾经没有我的故事 提交于 2019-12-01 15:47:19

问题


Having this JS 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();

I'm wondering in what order will the alerts show up - will it be in the order the events were triggered by click() or could it be random?

I'm asking about documented/standardised behaviour, not about what browsers currently implement.


回答1:


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');



回答2:


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



来源:https://stackoverflow.com/questions/7077179/javascript-event-handlers-execution-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!