jquery - $(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){}) -
i trying find out difference between
$(document).on('click', '#id', function(){});
and
$('#id').on('click', function(){});
i've not been able find info on if there difference between two, , if difference may be.
can please explain if there difference @ all?
the first illustration demonstrates event delegation. event handler bound element higher dom tree (in case, document
) , executed when event reaches element having originated on element matching selector.
this possible because dom events bubble tree point of origin. if click on #id
element, click event generated bubble through of ancestor elements (side note: there phase before this, called 'capture phase', when event comes downwards tree target). can capture event on of ancestors.
the sec illustration binds event handler straight element. event still bubble (unless prevent in handler) since handler bound target, won't see effects of process.
by delegating event handler, can ensure executed elements did not exist in dom @ time of binding. if #id
element created after sec example, handler never execute. binding element know in dom @ time of execution, ensure handler attached , can executed appropriate later on.
jquery syntax
No comments:
Post a Comment