gpt4 book ai didi

javascript - jQuery .on() 委托(delegate)与匹配嵌套元素的选择器

转载 作者:行者123 更新时间:2023-11-28 06:56:34 26 4
gpt4 key购买 nike

// Example A
$("#delegate").on("click", function(event) {
// executes on click on any descendant of #delegate or self (not a delegate at all)
// 'this' is #delegate
});


// Example B
$("#delegate").on("click", "#outer", function(event) {
// executes on click on any descendant of #outer or self
// 'this' is #outer or #inner (depends on the actual click)
});

$("#delegate").on("click", "#inner", function(event) {
// executes on click on any descendant of #inner or self (nothing happens when clicking #outer)
// 'this' is #inner
});


// Example C (now it's getting weird)
$("#delegate").on("click", "div", function(event) {
// executes twice, when clicking #inner, because the event passes #outer when bubbling up

// one time 'this' is #inner, and the other time 'this' is #outer
// stopPropagation() // actually prevents the second execution
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="delegate">
<div id="outer">
outer
<div id="inner">
inner
</div>
</div>
</div>

你如何从逻辑上解释这种行为?

只有一个点击事件,该事件从 #inner 开始,冒泡通过 #outer,最后到达 #delegate

该事件被#delegate 的处理程序(准确地)捕获一次。该处理程序检查事件的历史记录是否包含任何 div 元素。

如果适用,则应调用回调函数一次。这就是我所期望的。 “单个事件、单个处理程序、单个条件、单个回调”。

如果你看看 stopPropagation() 行为,事情会变得更加疯狂。尽管事件已经到达#delegate,您实际上可以避免第二次执行。 stopPropagation(在这里不应该工作。

委托(delegate)逻辑的实现过程中到底施了什么“魔法”?事件冒泡和程序流是否以任何方式分开?

请不要首先发布“实用建议”(“使用 xyz 代替!”)。我想了解为什么代码会这样工作。

最佳答案

因为您以两种方式在所有 div 上绑定(bind)了事件:

  1. 使用元素 div 的 id 属性。
  2. 使用元素 div 的标签名称。

因此,如果您 event.stopPropagation(); 在最后一个上,警报仍然会出现两次,因为您已经点击了 div 以及 #inner (例如。)

检查下面的代码片段。

$("#delegate").on("click", function(event) {
alert(this.id);
});

/*
$("#delegate").on('click', "#outer", function(event) {
alert(this.id);
});

$("#delegate").on('click', "#inner", function(event) {
alert(this.id);
});

*/
// now it's getting weird
$("#delegate").on("click", "div", function(event) {
event.stopPropagation();
alert(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="delegate">
<div id="outer">
outer
<div id="inner">
inner
</div>
</div>
</div>

关于javascript - jQuery .on() 委托(delegate)与匹配嵌套元素的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32523666/

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