gpt4 book ai didi

javascript - 单击事件和命名空间单击事件 - 哪个先触发,stopPropagation() 会取消其中一个吗?

转载 作者:行者123 更新时间:2023-11-29 21:05:23 25 4
gpt4 key购买 nike

示例:基础下拉菜单具有命名空间事件 click.fndtn.dropdown。他们的代码绑定(bind)到它,但不是纯 click

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

  1. 哪个事件先触发?

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

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

最佳答案

1. Which even fires first?

jQuery 确保它们按照它们被附加的顺序被触发(这也是几年前的标准)。

2. If I call event.stopPropagation() in click handler will that cancel click.fndtn.dropdown handler?

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

3. If I call event.stopPropagation() in click.fndtn.dropdown handler will that cancel click handler?

不,但是 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>

关于javascript - 单击事件和命名空间单击事件 - 哪个先触发,stopPropagation() 会取消其中一个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44366418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com