1
<ul>
<li>A</li>
</ul>

$("li").click(function(){
    console.log("Hello");
});

$("ul").on("click", "li", function(){
   console.log("Hello");
});

$("ul").append('<li>B</li>');

Hi everyone, when I press on "A", I have 2 "Hello"-logs in console, and when I press "B", it's only one "Hello", that comes from UL event handler.

Can someone explain that behavior?

Thank you.

Drevo
  • 3
  • 2
  • Possible duplicate of [Attaching event to future elements using jquery](http://stackoverflow.com/questions/21522499/attaching-event-to-future-elements-using-jquery) – edhurtig Jun 08 '16 at 07:14

2 Answers2

0

This is because the B <li> that you append does not get the onclick event handler attached to it because it did not exist in the DOM when you did:

$("li").click(function(){
    console.log("Hello");
});

You will need to register an onclick event handler with the B li individually with something like this (sorry, this is a very poor example):

$b = $('<li/>')
$b.text('B')
$b.click(function(){ console.log("Hello"); })
$("ul").append($b);
edhurtig
  • 2,331
  • 1
  • 25
  • 26
0

The first click event handler on the "li" tag works as expected on A because A existed when the handler was created. It doesn't work on B because B didn't exist when the handler was created.

The second click event handler on the "ul" tag is also catching the click on A through it's parent. In addition, it is also able to catch the click on B because the "on" method is able to keep track of the dynamic children that you specified in the parameters.

Rick
  • 1,863
  • 2
  • 19
  • 46