jQuery事件处理-绑定到文档还是'body'元素? [英] jQuery event handling - bind to document or 'body' element?

查看:67
本文介绍了jQuery事件处理-绑定到文档还是'body'元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们要引用整个页面时,尤其是在绑定事件时,我注意到$(document)$('body')的使用.

I have noticed the use of $(document) and $('body') when we want to reference the entire page, especially when binding events.

$(document).on('click', '.myElement', function);

$('body').on('click', '.myElement', function);

在性能方面有何区别?如果$(document)将事件绑定到整个HTML文档,为什么我们不使用$('body')来绑定像click这样的事件?

What is the difference performance-wise? If $(document) binds the event to the entire HTML document, why do we not use $('body') to bind events like click instead?

请注意,此问题不是要使用ready函数,而是要使用.on().delegate()绑定.

Note that this question is not referring to the use of the ready function, but the use of .on() or .delegate() binding.

推荐答案

在性能方面有什么区别?

What is the difference performance-wise?

几乎可以肯定,或更准确地说,没有可测量的.理论上,$('body')必须在DOM中搜索body元素,但这将非常快.同样,由于bodydocument的子级,因此在document存在之前的十亿分之一秒的事件冒泡中将达到它.

Almost certainly none, or more accurately, nothing measurable. $('body') in theory has to search the DOM for the body element, but that's going to be very fast. Also, since body is a child of document, it will be reached in the bubbling of the event nanoseconds before document is.

但是有一些区别:

如果head中的脚本中使用了$('body'),并且没有延迟执行(例如ready等),则$('body')将找不到任何内容,并且不会挂任何处理程序.另一方面,$(document)会.

If you used $('body') in a script in the head and didn't delay execution of it (ready, etc.), $('body') wouldn't find anything and wouldn't hook up any handlers. $(document), on the other hand, would.

如果文档的主体没有填充视口,则至少在某些浏览器上,您将单击document而不是body:

If the body of the document doesn't fill the viewport, then on at least some browsers, you'll get a click on document but not on body:

$(document).on("click", function() {
  $("<p>document</p>").appendTo(document.body);
});
$('body').on("click", function() {
  $("<p>body</p>").appendTo(document.body);
});

body {
  border-bottom: 1px solid #060;
}

<p>The line marks the bottom of <code>body</code>. Click above and below the line to see where the click was caught. (Note the line will move as we append to <code>body</code>.)</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

当然,这不适用于您的$('body').on('click', '.myElement', function);,因为如果点击不在body之外,则不会通过.myElement ...

Of course, that doesn't apply to your $('body').on('click', '.myElement', function); because if the click is outside body, it's not going to pass through a .myElement...

对于全局处理程序,我使用$(document),而不使用$('body')(或$(document.body)),但这可能更多是出于习惯而非原因.

For global handlers, I use $(document), never $('body') (or $(document.body)), but that may well be more from habit than reason.

这篇关于jQuery事件处理-绑定到文档还是'body'元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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