JQuery elements created using .append (html) are not available

I have the following

<script> $(document).ready(function() { $(".mapLink").click(function(){ pos = $(this).attr("id"); alert(pos); }); }); </script> <a class="map" id="test">Test</a> 

When I click Test, I get a warning ... excellent. But I also have the following ...

 <script> $(document).ready(function() { $(".mapLink").click(function(){ pos = $(this).attr("id"); alert(pos); }); }); $(#emp").change(function(){ $("#existingAttendTime").html(''); $.ajax({ url: "existingAttendTime.php?emp=" + SelValue + "&time=0", cache: false, success: function(html){ $("#existingAttendTime").append(html); } }); }); </script> <a class="mapLink" id="test">Test</a> <div id="existingAttendTime"></div> 

When emp changes, it fires and gets the results from existingAttendTime.php and inserts it into a div, so now it looks something like ...

 <a class="mapLink" id="test">Test</a> <div id="existingAttendTime"><a class="mapLink" id="12345">Return Test</a></div> 

By clicking on "Test", I get a warning "test", but clicking on Return Test gives me nothing.

What am I doing wrong or what am I missing?

+2
jquery
Sep 29 '09 at 0:20
source share
3 answers

You need to bind the click handler in live mode, otherwise the new DOM nodes will not start it:

 $(document).ready(function() { $(".mapLink").live("click", function(){ pos = $(this).attr("id"); alert(pos); }); }); 

Previously, a plugin was used for live queries, but jQuery 1.3 integrated a limited version into the main file . Also note that only certain types of events work; change , submit , etc. will not, so you will have to explicitly bind the handler inside the same function that added the new node to the DOM.

+4
Sep 29 '09 at 0:24
source share

Event handlers connect to the DOM once, if you are manipulating the DOM, you need to either

  • A) manually bind event handlers
  • B) rely on jQuery.prototype.live

Most likely, it is more suitable for using B, so I suggest changing the click code to something like.

 $("a.mapLink").live("click", function(){ var pos = $(this).attr("id"); alert(pos); }); 

This will target any bindings that have been added using the DOM manipulation.

Link: http://docs.jquery.com/Events/live

And FYI you have to use var to declare pos in the current scope.

+3
Sep 29 '09 at 0:23
source share

When elements are added dynamically, the click handler will not be registered on new elements. Use .live() :

 $(document).ready(function() { $(".mapLink").live('click', function(){ pos = $(this).attr("id"); alert(pos); }); }); 
+2
Sep 29 '09 at 0:24
source share



All Articles