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.
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!'); });
Comments
Post a Comment