Javascript事件监听器 - 射击命令 [英] Javascript Event Listeners - Firing order

查看:56
本文介绍了Javascript事件监听器 - 射击命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个元素附加了多个事件侦听器,那么执行的顺序将基于事件绑定的位置/时间(从上到下位于代码中)。保证,100%的时间?

If an element has multiple event listeners attached, will the order of execution be based on where/when the events are bound (located in the code from top to bottom). Guaranteed, 100% of the time?

或者是否涉及任何随机性。那么在同一个元素上混合使用jQuery和vanilla事件监听器呢?

Or is there any "randomness" involved in this. What about mixing jQuery and vanilla event listeners on the same element?

推荐答案

(假设您正在讨论相同的事件类型和元素)事件处理程序将按照其中的顺序执行处理程序已注册。当您处理jQuery句柄或javascript处理程序(捕获阶段在冒泡之前运行)时,这是真的,而不是混合。

(Assuming you are talking about the same event type and element)The event handlers will get executed in the order in which the handlers are registered. This is true when you are dealing with either jQuery handles or javascript handlers(the capture phase runs before bubbling) alone, not mixed.

当你有混合处理程序时,jQuery会当第一次尝试为元素注册一个类型的处理程序时添加一个vanila处理程序,因此它将按顺序遵循vanilla处理程序的顺序(但是当jQuery自己的本机处理程序被触发时,所有jQuery处理程序都将被执行)

When you have mixed handlers, jQuery will add a vanila handler when it tries to register a handler of a type for the first time for an element, so it will follow the order of vanilla handlers in order(but all the jQuery handlers will be executed when the jQuery's own native handler is triggered)

var el = document.getElementById('clickme');

el.addEventListener('click', function() {
  snippet.log('o - 1');
});
el.addEventListener('click', function() {
  snippet.log('o - 2');
});

$('#clickme').click(function() {
  snippet.log('jq - 1(o -3)')
});
el.addEventListener('click', function() {
  snippet.log('o - 4');
});
$('#clickme').click(function() {
  snippet.log('jq - 2')
});
$('#clickme').click(function() {
  snippet.log('jq - 3')
});
el.addEventListener('click', function() {
  snippet.log('o - 5');
});
el.addEventListener('click', function() {
  snippet.log('o - 6');
});
$('#clickme').click(function() {
  snippet.log('jq - 4')
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<button id="clickme">This is for testing</button>

这篇关于Javascript事件监听器 - 射击命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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