Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>click()</code> binding you're using is called a "direct" binding which will only attach the handler to elements that <em>already exist</em>. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using <a href="http://api.jquery.com/on/"><strong><code>on()</code></strong></a>. </p> <blockquote> <p>Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.</p> </blockquote> <p><sup><a href="http://api.jquery.com/on/">Source</a></sup></p> <p>Here's what you're looking for:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var counter = 0; $("button").click(function() { $("h2").append("&lt;p class='test'&gt;click me " + (++counter) + "&lt;/p&gt;") }); // With on(): $("h2").on("click", "p.test", function(){ alert($(this).text()); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;h2&gt;&lt;/h2&gt; &lt;button&gt;generate new element&lt;/button&gt;</code></pre> </div> </div> </p> <p>The above works for those using jQuery version 1.7+. If you're using an older version, refer to the previous answer below.</p> <hr> <p><strong>Previous Answer</strong>:</p> <p>Try using <a href="http://api.jquery.com/live"><code>live()</code></a>:</p> <pre><code>$("button").click(function(){ $("h2").html("&lt;p class='test'&gt;click me&lt;/p&gt;") }); $(".test").live('click', function(){ alert('you clicked me!'); }); </code></pre> <p>Worked for me. <a href="http://jsfiddle.net/PzSYM/">Tried it</a> with jsFiddle.</p> <p>Or there's a new-fangled way of doing it with <a href="http://api.jquery.com/delegate/"><code>delegate()</code></a>:</p> <pre><code>$("h2").delegate("p", "click", function(){ alert('you clicked me again!'); }); </code></pre> <p><a href="http://jsfiddle.net/PzSYM/1/">An updated jsFiddle</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload