javascript - $('body').click('li', func) Vs $('li').click(func), Second option does not work? -
$('body').click('li', function(){ console.log('clicked - handler 1') }) $('li').click(function(){ console.log("clicked - handler 2") })
i adding 2 handlers li element
's click event using 2 different selector mechanisms. when click element, console log says,
clicked - handler 1
this means, second handler not added @ all. wrong selecting li element
directly instead of selecting body , li
?
the second option may not work in 1 of cases:
- "li" elements added dynamically page, , not on page load (in other words, when selector executed, there no matching elements @ time).
- the code posted executed before dom loaded (eg., placed in simple
<script>
tag).
if it's second, try this:
$(function() { $('li').click(function(){ console.log("clicked - handler 2") }) });
this code executed after dom loaded, , $('li') selector succeed.
the first option works because "body" dom element available attach event handlers (second selector acts filter event target, actual handler attached "body").
Comments
Post a Comment