Javascript - Difference between $(document).on(“click”, “selector”, function …); and $(“selector”).on(“click”, function …);

前端 未结 4 1726
抹茶落季
抹茶落季 2021-01-15 20:15

What is difference between these two codes ?

$(document).on(\'click\', \'.close_modal_window\', function(){
        alert(\"window closed\");
    });
         


        
4条回答
  •  余生分开走
    2021-01-15 21:10

    Above are two examples with button's click event:

    
    

    Look the difference.


    Here is an example with delegation:

    http://jsfiddle.net/xtz1np6d/

    and here one without delegation:

    http://jsfiddle.net/ketme18a/


    As you can see, elements created dinamically, aren't in the context when the function was created, and for that, they don't have any function assigned.


    I super recommend this lecture: Understanding Event Delegation


    But be cautious, had one time that I used event delegation and it crushed my niceScroll-plugin in iPad.

提交回复
热议问题