-1
 var post = '<img class="img_proids" src="image/thumbnail/' + usr_data[2] + '"/><div class="div_postcontent"><ul class="ul_postcontent">';
 post = post + '<li><a class="a_unames" href="#" usr_data[1] + '</a>';
 post = post + '<span class="bu_delpost">Delete this post<input type="hidden" value="'+ result[1] + '"/></span></li></ul></div><div class="float_clear"></div><br><hr><br>';
 p_type.after(post); // append the post here using jquery 

What I did is, when user posts some data, I don't want the entire page to refresh. So I have sent the data to server using ajax request and also appended the post contents to the page, using jQuery. But the event:

$("span.bu_delpost").click(function(){ // see 3rd line, span class='bu_delpost'

   var d_postid =  $(this).find("input").val();
   var p_type = $("#inp_type").val();

    $.post("ajax/ajx_dpost.php",{d_post:d_postid,type:p_type},function(result){
               alert(result)                
});

});

does not seem to work for appended posts but it seems to work for the posts which are loaded at the beginning from the database.

Why does this event does not work for the newly added span element? However CSS properties seems to work for this newly added elements but not the JavaScript events.

Note: The JavaScript events are written in jquery.posts.js file and are included to the html file using <script src="jquery/jquery.posts.js"></script>

halfer
  • 19,824
  • 17
  • 99
  • 186
niko
  • 9,285
  • 27
  • 84
  • 131

2 Answers2

2

Event delegation - As the element is dynamically added to the DOM

Change

$("span.bu_delpost").click(function()

to

$(document).on('click', 'span.bu_delpost', function()

This will attach the event on the document and will handle it when the event bubbles.

Always better idea to replace document with a staticParent container for the sake of performance.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
1

for JQuery 1.8+

 $(document).on('click', 'span.bu_delpost', function(e){ // see 3rd line, span class='bu_delpost'

       var d_postid =  $(this).find("input").val();
       var p_type = $("#inp_type").val();

        $.post("ajax/ajx_dpost.php",{d_post:d_postid,type:p_type},function(result){
                   alert(result)                
    });

    });

if you use version prior, you might use

$("span.bu_delpost").live('click', function (){
//here goes your code
});
simongus
  • 440
  • 2
  • 6