onClick 优先于javascript中的addEventListener? [英] onClick priority over addEventListener in javascript?

查看:23
本文介绍了onClick 优先于javascript中的addEventListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我有一个事件监听器来监听屏幕上的点击.屏幕上还有一个按钮.当我单击按钮时,事件侦听器将在 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的第三个参数是useCapture 标志.如果将其设置为 true,则在事件 downbutton 元素时将执行处理程序.但是,如果将其设置为 false,则在事件冒泡时将触发处理程序:

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

在您的示例中,onclick 应该在 body 标记 上的点击处理程序之前执行.如果你想颠倒执行顺序,你应该在bodycapture事件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆