单击事件和命名空间的单击事件 - 首先触发并将stopPropagation()取消其中一个?

时间:2017-06-05 10:02:31

标签: javascript jquery events

示例:foundation dropdown具有命名空间事件click.fndtn.dropdown。 他们的代码与它绑定,但不与纯click绑定。

当我绑定到同一元素的click事件时会发生什么?

  1. 哪个事件会先发生?

  2. 如果我在event.stopPropagation()处理程序中调用click会取消click.fndtn.dropdown处理程序吗?

  3. 如果我在event.stopPropagation()处理程序中调用click.fndtn.dropdown会取消click处理程序吗?

1 个答案:

答案 0 :(得分:2)

  

1。哪个甚至先发射?

jQuery确保它们按照它们所附加的顺序被触发(现在也是标准的,就像几年前一样)。

  

2。如果我在event.stopPropagation()处理程序中调用click将取消click.fndtn.dropdown处理程序?

不,但stopImmediatePropagation 如果您的处理程序是先注册的。

  

3。如果我在event.stopPropagation()处理程序中调用click.fndtn.dropdown将取消单击处理程序吗?

不,但stopImmediatePropagation如果首先注册该处理程序。

示例:

$("#ns-first-stop-prop").on("click.ns", function(e) {
  console.log("click.ns -- calling stopPropagation");
  e.stopPropagation();
});
$("#ns-first-stop-prop").on("click", function(e) {
  console.log("click -- calling stopPropagation");
  e.stopPropagation();
});

$("#plain-first-stop-prop").on("click", function(e) {
  console.log("click -- calling stopPropagation");
  e.stopPropagation();
});
$("#plain-first-stop-prop").on("click.ns", function(e) {
  console.log("click.ns -- calling stopPropagation");
  e.stopPropagation();
});

$("#ns-first-stop-immed").on("click.ns", function(e) {
  console.log("click.ns -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
$("#ns-first-stop-immed").on("click", function(e) {
  console.log("click -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});

$("#plain-first-stop-immed").on("click", function(e) {
  console.log("click -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
$("#plain-first-stop-immed").on("click.ns", function(e) {
  console.log("click.ns -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
<div><input type="button" id="ns-first-stop-prop" value="Namespaced First - calls stopPropagation"></div>
<div><input type="button" id="plain-first-stop-prop" value="Non-Namespaced First - calls stopPropagation"></div>
<div><input type="button" id="ns-first-stop-immed" value="Namespaced First - calls stopImmediatePropagation"></div>
<div><input type="button" id="plain-first-stop-immed" value="Non-Namespaced First - calls stopImmediatePropagation"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>