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

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

问题描述

我正在尝试使用 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:

当提供了 selector 时,事件处理程序被称为 delegated.当事件直接发生在绑定元素上时,不会调用处理程序,而是仅针对与选择器匹配的后代(内部元素)调用.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天全站免登陆