jQuery:在这种情况下正确使用.on()是什么?

All*_*n S 5 jquery events

考虑以下标记:

 <div class="parent">
     <div class="child">
         button
    </div>
 </div>
Run Code Online (Sandbox Code Playgroud)

我需要clickchild类上的事件上运行一个函数,我有以下两个选项:

 $(".parent").on("click", ".child", function(){....});
Run Code Online (Sandbox Code Playgroud)

 $(document).on("click", ".child", function(){....});
Run Code Online (Sandbox Code Playgroud)

使用直接parent作为目标与document自身之间的性能是否存在显着差异?对我来说使用document似乎是一个更健壮的选项(例如,如果更改了父类) - 如果我开始在所有地方开始使用此方法,只需要确保它不会导致问题.

PS child是在parent我正在使用的内部动态添加的.on()

rak*_*110 4

$(".parent").on("click", ".child", function(){....});
Run Code Online (Sandbox Code Playgroud)

将您的单击事件仅绑定到文档中存在的类“.parent”的那些元素,并且事件从目标(“.child”)冒泡到附加处理程序的元素。这比将其添加到文档中要好得多,将其添加到文档中就像

$(document).on("click", ".child", function(){....});
Run Code Online (Sandbox Code Playgroud)
  1. 将单击事件从文档中发生的目标一直冒泡到正文和文档元素。

  2. 正如 @Woff 提到的,在删除 .parent 元素时,绑定处理程序不会被删除。