Friday, April 8, 2011

Appending HTML w/click event using jQuery

I want to append some HTML inside this div, and the HTML has to have a click event on it also.

    <div id="myID">
        <p>hello, world!</p>
    </div>

I want to insert a new div inside of the above div, and I want a click event on the new HTML I insert there. There will be some dynamic text inside the new div so it has to by dynamically created.

How can it be done?

From stackoverflow
  • What about :

    $("#myID").click(
      function () {
         var someText = "my dynamic text";
         var newDiv = $("<div>").append(someText).click(function () { alert("click!"); });
         $(this).append(newDiv);
      }
    )
    
  • As of jQuery 1.3, this will work:

    <div class="myClass">
    <p>hello, world!</p>
    </div>
    
    
    $(".myClass").live("click", function(){
        $(this).after("<div class='myClass'><p>Another paragraph!</p></div>");
    });
    

    See more about live events on this page:

    http://docs.jquery.com/Events

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.