0

This is the task I am trying to implement:

after an element "a" is clicked, jQuery generated some other elements, for example, a "p". Then if the "p" generated by JS is clicked, a msgbox pops up.

This is the example code I wrote: http://jsfiddle.net/ux3n8/

$(".original").click(function(){
  var p=$('<p>').text("hahahahahaha");
  $(p).addClass("createdByJS");
  $(".main").append($(p));
});

$(".createdByJS").click( function(){
  alert("hello World!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <a class="original">test</p>
</div>

If I remove the event of $("a").click(function(), but still have the jQuery to generate the "p" there, everything works well. But if the "p" is generated on a click of "a", then I cannot add further jQuery functions to it.

I am still new to coding. It would be really appreciated if someone could help me find a solution.

Thank you very much!

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
user3352464
  • 315
  • 1
  • 3
  • 14

1 Answers1

2

You need to delegate the event to an element which is present at the time of adding the new element. In this case document.

http://learn.jquery.com/events/event-delegation/

Demo:http://jsfiddle.net/robschmuecker/ux3n8/2/

$(".original").click(function () {   
  var p = $('<p>').text("hahahahahaha");
  $(p).addClass("createdByJS");
  $(".main").append($(p));
});

$(document).on('click', '.createdByJS', function () {
  alert("hello World!");
});
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Rob Schmuecker
  • 8,934
  • 2
  • 18
  • 34
  • You could also delegate on `.main` like this `$('.main').on('click', '.createdByJS',...` http://jsfiddle.net/robschmuecker/ux3n8/4/ – Rob Schmuecker Jul 20 '14 at 20:59