How to save event handlers, when we set new html for element?

Posted by Kai on Stack Overflow See other posts from Stack Overflow or by Kai
Published on 2011-01-13T09:50:25Z Indexed on 2011/01/13 9:54 UTC
Read the original article Hit count: 206

Filed under:
|
|

I have simple html markup:

<div id="cont">Some text here
  <div class="wrap" style="border: 1px solid black;display: inline;"> block element here
  </div> and another text</div>

And jQuery code:

$(function(){
  $(".wrap").click(function(){
      $("#cont").html($("#cont").html().replace(/text/g, "letter"));
    alert("Click!");
  });
  $("#d1").click(function(){
    alert("#d1 clicked!");
  });
});

I expect that click event will be fire any time you clicked by the #d1 div, but when we clicked by .wrap it neve fire again. I understand why it has such behavior, but how to solve it?
In my code I can't set click event for #d1 after $("#cont").html($("#cont").html().replace(/text/g, "letter")) because I don't now at execution time if event was set.
You can try example on JSBin

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery