When using jQuery on(), why use (document) vs. the element itself?

后端 未结 6 544
情书的邮戳
情书的邮戳 2020-11-27 07:49

I\'d like a jQuery expert in their own words to explain why the $(document) identifier is recommended by others for jQuery\'s on() statement vs just using an element itself<

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 08:25

    There's nothing "recommended" about this. The first snippet sets up a "delegated" event, the latter is a "direct" one. The documentation for on() explains these in depth.

    Delegated events are necessary when you need to listen to events for elements that don't exist yet - ones that will be created dynamically after, for example, an AJAX call. They can also sometimes be better performance-wise - you need less memory to attach a "real" event handler to the document object, than to 1000 buttons.

    I'd say it's still preferrable to use direct event handlers when you can, or attach delegate events to an element as close to the real event sources as you can. Having all event handlers on the document object is probably terrible for performance - you have to match every event fired against all the selectors. It's also probably needed if you need to stop an event from bubbling - if all events are caught on the document, they've already bubbled as far as they'll go.

提交回复
热议问题