onClick priority over addEventListener in javascript?(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
,则在事件 down 到 button
元素时将执行处理程序.但是,如果将其设置为 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
标记 上的点击处理程序之前执行.如果你想颠倒执行顺序,你应该在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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:onClick 优先于javascript中的addEventListener?


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01