Difference between .on() functions calls

前端 未结 3 956
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 13:23

What is the difference between the following?

$(document).on(\"scroll\",\".wrapper1\", function(){
   $(\".wrapper2\")
    .scrollLeft($(\".wrapper1\").scrol         


        
3条回答
  •  爱一瞬间的悲伤
    2020-11-30 13:47

    The difference is in the first case the listener is targeting the document, so if you don't have .wrapper1 on page load and add it additionally (AJAX or some other way) the event will still fire (since the document is always there).

    In the second case if .wrapper1 is added dynamically the event won't fire, even thought you're using .on() since you don't have an element to bind that .on() to.

    That being said second variant should be used only when the selected element is not dynamically created and the first one in the opposite case.

提交回复
热议问题