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

后端 未结 6 546
情书的邮戳
情书的邮戳 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:03

    $(*selector*).on(*event*, function(){})
    

    will apply only for elements which is already load in page at the moment of script run. If in future, will appear new elements, the event handler will be not work.

    $(document).on(*event*, *selector*, function(){} 
    

    will execute event handler even the elements with same selector will appear on page after script run.

    So, if you have some elements, which can appear after in random time, use

    $(document).on()
    

    else use

    $(*selector*).on();
    

提交回复
热议问题