onClick优先于JavaScript中的addEventListener? [英] onClick priority over addEventListener in javascript?
问题描述
现在,我有一个事件侦听器,用于侦听屏幕上的单击.屏幕上还有一个按钮.当我单击按钮时,事件监听器将在onclick之前执行.有什么方法可以使onclick具有更高的优先级?
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 before the onclick. Is there a way I can make onclick have higher priority?
<script>
document.body.addEventListener('click',function(){alert('1');}, false);
function clicked() {
alert('2');
}
</script>
<button onclick="clicked()">Click this</button>
单击按钮还会触发事件处理程序.当我单击按钮时,1在2之前显示.我想先显示2个.
Clicking the button also triggers the event handler. 1 shows before 2, when I click the button. I want 2 to show first.
推荐答案
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 |
------------------------------------------
来自: http://www.quirksmode.org/js/events_order.html#链接4
在您的示例中,应在body
标记上的点击处理程序之前 执行onclick
.如果要反转执行顺序,则应在body
处capture
事件.
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
.
这篇关于onClick优先于JavaScript中的addEventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!