Should all jquery events be bound to $(document)?

后端 未结 4 1053
情深已故
情深已故 2020-11-21 07:48

Where this is coming from

When I first learned jQuery, I normally attached events like this:

$(\'.my-widget a\').click(function() {
    $(this).tog         


        
4条回答
  •  感情败类
    2020-11-21 08:39

    Event delegation is a technique to write your handlers before the element actually exist in DOM. This method has its own disadvantages and should be used only if you have such requirements.

    When should you use event delegation?

    1. When you bind a common handler for more elements that needs same functionality. (Ex: table row hover)
      • In the example, if you had to bind all rows using direct bind, you would end up creating n handler for n rows in that table. By using delegation method you could end up handling all those in 1 simple handler.
    2. When you add dynamic contents more frequently in DOM (Ex: Add/remove rows from a table)

    Why you should not use event delegation?

    1. Event delegation is slower when compared to binding the event directly to element.
      • It compares the target selector on every bubble it hits, the comparison will be as expensive as it is complicated.
    2. No control over the event bubbling until it hits the element that it is bound to.

    PS: Even for dynamic contents you don't have to use event delegation method if you are bind the handler after the contents get inserted into DOM. (If the dynamic content be added not frequently removed/re-added)

提交回复
热议问题