首页 > 解决方案 > 为什么要在绑定 jQuery 事件监听器之前指定“document”或“body”?

问题描述

在 jQuery 中,有很多方法可以将动作绑定到事件,并为它们添加监听器。有了这个我没有问题。

但我无法理解的是,在监听事件之前为此指定“正文”或“文档”的目的是什么?

考虑以下代码:

$(".example-button").click(function() {
  $(this).text("I have been clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="example-button" role="button" type="button">I have not been clicked yet.</button>
<button class="example-button" role="button" type="button">I have not been clicked yet.</button>

这会将事件“click”绑定到具有类“example-button”的按钮,当它们被单击时,它将更改相应的按钮文本以让您知道。

但是,我经常看到程序员(通常是经验丰富的程序员)编写以下代码:

$("body").on("click", ".example-button", function() {
  $(this).text("I have been clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="example-button" role="button" type="button">I have not been clicked yet.</button>
<button class="example-button" role="button" type="button">I have not been clicked yet.</button>

这实现了与第一个代码块相同的感知效果。

我的问题是,为什么?

更具体地说,为什么要将它绑定到文档或正文,然后检查点击呢?那不是额外的冗余代码部分吗?

为了证明这一点,我想出了一个理论,也许通过指定点击绑定到正文将确保正文已加载 - 但这不正确,因为 $("body").on("click") 等不等于 $(document).ready()。

任何人都可以提供更多的见解吗?我似乎无法在 jQuery 文档中找到我的答案,因为它默认假设我正在寻找上述内容

$(document).ready().

标签: javascriptjqueryeventsevent-delegation

解决方案


为什么使用委托事件监听器?

1) 内容尚不存在

//#container is empty, but we will create children in the future
//we can use a delagate now that will handle the events from the children
//created later
$('#container').on('click', '.action', function (e) {
  console.log(e.target.innerText);
});

//lets create a new action that didn't exist before the binding
$('#container').append('<button class="action">Hey!  You Caught Me!</button>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

2)内容存在,但变化

//#container has an existing child, but it only matches one of our
//delegate event bindings.  Lets see what happens when we change it
//so that it matches each in turn

$('#container').on('click', '.action:not(.active)', function (e) {
  console.log('Awww, your not active');
  $(e.target).addClass('active');
});

$('#container').on('click', '.action.active', function (e) {
  console.log('Hell yeah!  Active!');
  $(e.target).removeClass('active');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <button class="action">Hey! You Caught Me!</button>
</div>

为什么在委托事件侦听器上使用非委托事件侦听器?

1) 内容是静态的和预先存在的

要么是因为您知道内容是静态的并且不会改变,而且您不需要内容。否则,您可能更喜欢使用委托,这作为开发人员的偏好很好。

2)您可以防止事件冒泡

但是,使用非委托事件侦听器也可以与委托结合使用,以防止操作。考虑以下:

//#container has three children.  Lets say we have a delegate listener for
//the buttons, but we only want it to work for two of them.  How could we
//use a non-delegate to make this work?

//delegate that targets all the buttons in the container
$('#container').on('click', 'button', function (e) {
  console.log('Yeah!');
});

$('.doNotDoSomething').on('click', function (e) {
  console.log('Do not do the delegate logic');
  
  //by stopping the propagation of the click event, it will not bubble up
  //the DOM for the delegate event handler to process it.  In this way, we
  //can prevent a delegate event handler from working for a nested child.
  e.stopPropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <button class="doSomething">Do It!</button>
  <button class="doNotDoSomething">Nooooo!</button>
  <button class="doSomethingElse">Do This Instead!</button>
</div>

3) 你希望你的绑定是可移动的

可能想要使用非委托事件侦听器的另一个原因是因为它们附加到元素本身。因此,鉴于此,如果您删除元素,绑定也会随之消失。虽然这可能是您希望元素始终存在绑定的动态内容的问题,但在某些情况下您可能希望发生这种情况。


推荐阅读