Javascript 事件优先级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19716560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Event Priority
提问by Magic Lasso
With the different ways of adding events in javascript, do any of them take priority like css classes do? For example will an inline onclick even always fire before one added with addEventListener?
随着在 javascript 中添加事件的不同方式,它们中的任何一个都像 css 类一样优先吗?例如,内联 onclick 是否总是在添加 addEventListener 之前触发?
If not, is there any way to give an event priority?
如果没有,有没有办法给事件优先级?
采纳答案by ma?ek
Yes
是的
An inline onclick
handler is going to bind asthe DOM is loading
内联onclick
处理程序将绑定作为在DOM加载
Whereas anything you add with .on
or .addEventListener
will have to wait for the DOM element to load first.
而您添加的任何内容.on
或.addEventListener
将必须等待 DOM 元素首先加载。
See here: http://jsfiddle.net/DmxNU/
见这里:http: //jsfiddle.net/DmxNU/
Your html
你的html
<a href="#" onclick="console.log('hello');">click</a>
Your js (jQuery in this case)
您的 js(在本例中为 jQuery)
$(function() {
$("a").click(console.log.bind(console, "world"));
});
Output
输出
hello
world
Explanation
解释
I'm not sure where this would be documented, but think about it this way. If you're going to use the DOM API to query an element and then add an event listener, that element has to be loaded first. If that element already contains an onclick
attribute, that will already be attached first.
我不确定这会记录在哪里,但请以这种方式考虑。如果您打算使用 DOM API 来查询一个元素,然后添加一个事件侦听器,则必须先加载该元素。如果该元素已经包含一个onclick
属性,则该属性将首先被附加。
回答by Ibrahim Najjar
JavaScript events don't take any priorities. When and event is fired it is added to an event queue and executed as soon as possible.
JavaScript 事件没有任何优先级。当和事件被触发时,它被添加到事件队列并尽快执行。
You can claim that it is a general rule that onclick attribut events will always trigger first, and that will always be true, but it's not because they are prioritized.
您可以声称 onclick 属性事件始终首先触发是一个普遍规则,并且始终如此,但这并不是因为它们具有优先级。
Quoted from @Kevin B's comment
引自@Kevin B 的评论