我试图理解使用 jQuery .on() method 的直接和委托(delegate)事件处理程序之间的特殊区别。 。具体来说,本段最后一句:
When a
selector
is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
“为任何元素运行处理程序”是什么意思?我做了一个test page尝试这个概念。但以下两种构造都会导致相同的行为:
$("div#target span.green").on("click", function() {
alert($(this).attr("class") + " is clicked");
});
或者,
$("div#target").on("click", "span.green", function() {
alert($(this).attr("class") + " is clicked");
});
也许有人可以引用不同的例子来澄清这一点?谢谢。
最佳答案
案例 1(直接):
$("div#target span.green").on("click", function() {...});
==嘿!我希望 div#target 中的每个 span.green 都能监听:当您被点击时,执行 X。
案例 2(委托(delegate)):
$("div#target").on("click", "span.green", function() {...});
== 嘿,div#target!当您的任何“span.green”子元素被单击时,对它们执行 X 操作。
换句话说...
在情况 1 中,每个跨度都已单独给出指令。如果创建新的跨度,他们将不会听到指令,也不会响应点击。每个跨度都直接负责自己的事件。
在情况2中,只有容器被给予指令;它负责代表其子元素注意到点击。捕获事件的工作已被委派。这也意味着该指令将对将来创建的子元素执行。
关于javascript - 直接与委托(delegate) - jQuery .on(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096091/