问题
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