1

I'm sending ajax request and i have appended the result on a div. After this append if i want to click on a link appended (exec jquery click function), why click function doesen't work? (Sorry for bad english :P )

EDIT:

jQuery('.more').live("click",function() {
    var ID = jQuery(this).attr("id");
    if(ID) {
        jQuery("#more"+ID).html('<img src="template/css/images/moreajax.gif" />');
    jQuery.ajax({
        type: "POST",
        url: "loadmore.php",
        data: "lastid="+ ID, 
        cache: false,
        success: function(html){
            $("#contentWall").append(html);
        jQuery("#more"+ID).remove(); // removing old more button
        }
    });
    } else {
        jQuery(".morebox").html('The End');// no results
    }
return false;
});
Lèse majesté
  • 7,923
  • 2
  • 33
  • 44
fdisotto
  • 95
  • 2
  • 7
  • What does your JS console say? – Lèse majesté Jul 02 '12 at 13:50
  • 1
    You'll need to show us what code you have now, but my guess is that you are creating your event handlers before you append your code. Unless you delegate your events, you have to create your elements before you can attach event handlers to them – jackwanders Jul 02 '12 at 13:51
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Mar 02 '14 at 19:17

3 Answers3

7

You need to use .live() or .on(), depending on your jQuery version for this to work.

The regular .click() only applies to the elements that are currently in the DOM, not for future additions.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

Without more information is hard to be sure but probably your problem is that you're using something like this

// this only bind click handler to existing elements matching selector
$('#mycontainer a').click(function(){...}) 

And you need to use on for covering dynamically added elements.

// this bind click handler to current and future elements matching selector
$('#mycontainer').on('click','a',(function(){...}) 
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

When your page originally loads, your click event is bound to your links. This means that any new links introduced to the DOM after that don't have the click event bound to them. You need to bind the click event to the link you are appending:

$(newlink).click(function(event){
    // your onclick code
});
$(mydiv).append(newlink);
hellsgate
  • 5,905
  • 5
  • 32
  • 47