0

I want to delete the paragraph that jquery create when I click the paragraph.

<p class="test">cutsom event</p>
<button class="clcik">click</button>

jquery:

$(function () {
"use strict";

$(".test").on("click", function () {
    $(this).hide();
});

$("button").on("click", function () {
    $("<p>delet this paragraph</p>").insertAfter($(this));
});

$("p").on("click", function () {
    (this).hide();
});
});

update: @LinkinTED solved it, but dose there best practice for for that code?

akram
  • 71
  • 6

2 Answers2

6

When you call this:

$("p").on("click", function () {
    $(this).hide();
});

your paragraph doesn't exist yet, so this doesn't actually do anything.

You can do $('body').on('click','p', function(){}) instead

GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
TKoL
  • 13,158
  • 3
  • 39
  • 73
1

Your function will work on the paragraphs that are static in the page. However the dynamic added paragraphs won't. You'll need to bind the function on a static element.

$(function () {
  /* obsolute while the last function is the same 
  $(".test").on("click", function () {
    $(this).hide();
  });*/

  $("button").on("click", function () {
    $("<p>delet this paragraph</p>").insertAfter($(this));
  });

  $(document).on("click", "p", function () {
    $(this).hide();
//  ^------ you forgot the $ here
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="test">cutsom event</p>
<button class="click">click</button>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59