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:

  1. "li" elements added dynamically page, , not on page load (in other words, when selector executed, there no matching elements @ time).
  2. 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

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -