bind events on body or document?

折月煮酒 提交于 2021-02-18 20:11:44

问题


sometimes the users bind the events on $('body') and sometimes on $(document)

$(document).on('click', someAction);

$('body').on('click', someAction);

Is there some reason to prefer one to another?


回答1:


For me, there is mainly one reason to bind the events on $(document) and not to $('body'):

no need to wait domReady (document is available before everything else)




回答2:


Short answer most likely is, no, not really.

The reason someone is doing it should always be that he requires to catch an event globally in his markup. Since the <body> tag should follow as direct sibling to <html>, all events bubbling phase will end there.

<html>
    <body>
         <div>
         </div>

Every click event on <div> would bubble up to <body> as well as <html> (if not stopped manually). So for that usecase it should not make any difference.




回答3:


There is some difference in speed, not much else. Someone has already done the work though so I'll just point you the link.

http://jsperf.com/jquery-body-vs-document-body-selector

However, in direct relation to your code there, there is one major difference. $(document).on('click', someAction); will affect anywhere on the document viewing area, whereas $('body').on('click', someAction); Might not affect as much area as body can have an independent height and width.



来源:https://stackoverflow.com/questions/13687269/bind-events-on-body-or-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!