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

后端 未结 6 554
情书的邮戳
情书的邮戳 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条回答
  •  旧时难觅i
    2020-11-27 08:06

    Actually the best solution in a case such as this is not using the $(document) neither the specific element like $("selector").

    The best approach is using the container of the element and bind the element selector in the on function. By doing this you avoid unnecessary event bubbling to the document.

    So the code should look like:

    $("this_is_the_container").on('event','my_element_selector',function(){
    // do some stuff here
    })
    

提交回复
热议问题