Search code examples
javascripthtmljqueryjquery-eventshtml-rendering

Bind an event handler on a element who's inserted by the jQuery .html() function


I render some new content with .html() after ajax call into my site.

$.getJSON(scriptURL, $("#domainForm").serialize(), function(data) {
  $("#checkedDomain").html(data['html']) 
});

Now. How can I bind an event handler to div tags in that replaced html without including the script again? now the html the I render into my site looks like this:

<script type="text/javascript" src="myScript.js"/>
<div id="tagWithHandlerOn"/>someButton</div>

I want to get rid of the <script> Tag because it's a redeclaration and if I load the same content into that tag again two scripts are going to be loaded. Any hint?


Solution

  • Try using jQuery.live()


    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().