jquery - Click event doesn't work on dynamically generated elements -


this question has answer here:

<html> <head>     <script type="text/javascript" src="jquery.js"></script>     <script type="text/javascript">          $(document).ready(function() {              $("button").click(function() {                 $("h2").html("<p class='test'>click me</p>")             });                 $(".test").click(function(){                 alert();             });         });      </script> </head> <body>     <h2></h2>     <button>generate new element</button> </body> </html> 

i trying generate new tag class name test in <h2> clicking button. defined click event associated test. event doesn't work.

can help?

the click() binding you're using called "direct" binding attach handler elements already exist. won't bound elements created in future. that, you'll have create "delegated" binding using on().

delegated events have advantage can process events descendant elements added document @ later time.

source

here's you're looking for:

var counter = 0;    $("button").click(function() {      $("h2").append("<p class='test'>click me " + (++counter) + "</p>")  });    // on():    $("h2").on("click", "p.test", function(){      alert($(this).text());  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  <h2></h2>  <button>generate new element</button>

the above works using jquery version 1.7+. if you're using older version, refer previous answer below.


previous answer:

try using live():

$("button").click(function(){     $("h2").html("<p class='test'>click me</p>") });      $(".test").live('click', function(){     alert('you clicked me!'); }); 

worked me. tried it jsfiddle.

or there's new-fangled way of doing delegate():

$("h2").delegate("p", "click", function(){     alert('you clicked me again!'); }); 

an updated jsfiddle.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -