直接与委派 - jQuery .on() [英] Direct vs. Delegated - jQuery .on()

查看:124
本文介绍了直接与委派 - jQuery .on()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 direct 和委派的事件处理程序之间的这种特殊区别/rel =noreferrer> jQuery .on()方法。具体来说,本段最后一句:

I am trying to understand this particular difference between the direct and delegated event handlers using the jQuery .on() method. Specifically, the last sentence in this paragraph:


当提供选择器时,事件处理程序称为委派。当事件直接发生在绑定元素上时,不会调用处理程序,但仅适用于与选择器匹配的后代(内部元素)。 jQuery将事件从事件目标起泡到附加处理程序的元素(即最里面到最外层的元素),并为匹配选择器的路径上的任何元素运行处理程序。

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.

运行任何元素的处理程序是什么意思?我制作了一个测试页来试验这个概念。但是以下两种结构都会导致相同的行为:

What does it mean by "runs the handler for any elements"? I made a test page to experiment with the concept. But both following constructs lead to the same behavior:

$("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");
});

也许有人可以参考另一个例子来澄清这一点?谢谢。

Maybe someone could refer to a different example to clarify this point? Thanks.

推荐答案

案例1(直接):

$("div#target span.green").on("click", function() {...});

==嘿!我希望div#target中的每个span.green都能听到:当你点击它时,做X.

== Hey! I want every span.green inside div#target to listen up: when you get clicked on, do X.

案例2(委托):

$("div#target").on("click", "span.green", function() {...});

==嘿,div#target!当点击任何span.green的子元素时,请用它们做X.

== Hey, div#target! When any of your child elements which are "span.green" get clicked, do X with them.

换句话说......

在案例1中,每个跨度都已单独给出指令。如果创建了新跨度,他们将听不到指令,也不会响应点击。对于自己的事件,每个范围直接负责

In case 1, each of those spans has been individually given instructions. If new spans get created, they won't have heard the instruction and won't respond to clicks. Each span is directly responsible for its own events.

在案例2中,只有容器被给予指令;它负责代表代表其子元素。捕获事件的工作已经委派。这也意味着将对将来创建的子元素执行该指令。

In case 2, only the container has been given the instruction; it is responsible for noticing clicks on behalf of its child elements. The work of catching events has been delegated. This also means that the instruction will be carried out for child elements that are created in future.

这篇关于直接与委派 - jQuery .on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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