将click事件绑定到文档是否比将其绑定到主体更好? [英] Is binding a click event to document better than binding it to body?

查看:69
本文介绍了将click事件绑定到文档是否比将其绑定到主体更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题就在两者之间

$("body").click(function(e){});$(document).click(function(e){});

哪个更有效或更明智?还是取决于情况?

which is more efficient or advisable? Or does it depend on the situation?

老实说,我既可以互换使用它们,也没有任何区别,直到我好奇并在这里问了这个问题.

Honestly I have used them both interchangeably and haven't seen any differences until I got curious and asked this question here.

推荐答案

如果页面高度小于视口高度,则单击页面下方的视口将不会触发'body'单击处理程序,而只会触发document点击处理程序.

If the page height is smaller than the viewport height, then clicking on the viewport below the page will not trigger the 'body' click handler, but only the document click handler.

实时演示: http://jsfiddle.net/simevidas/ZVgDC/

在演示中,尝试单击文本下方的区域,您将看到只有document单击处理程序会执行.

In the demo, try clicking on the area below the text, and you will see that only the document click handler executes.

因此,最好将处理程序绑定到Document对象.

Therefore, it is better to bind the handler to the Document object.

这篇关于将click事件绑定到文档是否比将其绑定到主体更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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