-3

My problem is:

When I press the "Show numbers" button, Javascript dynamically create two elements whose class is "number". I expect the computer will console the text of the element which I click. But no matter how hard I try to click the elements, my computer console nothing.

HTML (Pug):

 button#btn show numbers
 .numberlist

Produced HTML:

<button id="btn">show numbers</button>
<div class="numberlist"></div>

JavaScript:

 $("#btn").click(
   function(){
     $(".numberlist").html("<div class='number'>1</div><div class='number'>2</div>");
   }
 );

 $(".number").click(
   function(){
     console.log("You click number "+$(this).text());
   }
 );

It's the page on Codepen.

1 Answers1

3

You need to use event delegation; since $(".number") is targeting an element with class="number" and assigning an event, that element needs to be present when the function is defined. Since you're appending (via .html) that element, it does not exist when your function is declared. To handle this, use:

$("body").on("click", ".number", function(){
  console.log("You click number "+$(this).text());
});

This will assign the click handler to any elements in body that have a class of .number, even ones that are added dynamically.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • Thank you guys!!! I know what the problem is. It's my first time to post a question on StackOverFlow and I'm really nervous about my poor English. I just learn about how to dynamically add the html, so I didn't sense the problem when I coding. Thanks again!!! – Winnie_Hung Jun 18 '18 at 17:55