0

I tried this

$(document).ready(function(){
    var conntent = $("#conntent");
    $('#form_post').submit(function(){
        if($("#set").val() != ''){
             $.post('post.php', $("#form_post").serialize(), function(data){
                 conntent.append('<div class="item"><span>' + data + 
                 '</span></div>');
             });
        }
        $("#set").val('');
        return false;
     });    

   //Then I try to click on new the new element

        $('span').click(function(){
            alert("OK");
        });
   });

However, after this I can't use click on the spans

I think is it possible after appending them that the are not part of the DOM. Any suggestions?

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
John Doe
  • 163
  • 1
  • 3
  • 7
  • possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – JJJ Dec 29 '11 at 19:03
  • Also see [`.on()`](http://api.jquery.com/on/) if you're using jQuery 1.7 or later. – JJJ Dec 29 '11 at 19:04

2 Answers2

2

Is this code:

$('span').click(function(){
    alert("OK");
});

running before this code:

conntent.append('<div class="item"><span>' +data + '</span></div>');

This is very much a possibility since the POST is asynchronous.

You can use jQuery's .live() or .delegate() to bind to elements which haven't been added to the DOM yet. That way when they are dynamically added the click event will automatically bind to them.

Alternatively, if you just want that call to .click(function()) to happen after the POST then you can call it in the response rather than outside of the whole thing. Something like this:

$.post('post.php', $("#form_post").serialize(), function(data){
    conntent.append('<div class="item"><span>' +data + '</span></div>');
    $('span').click(function(){
        alert("OK");
    });
});

Personally I'd opt for the .delegate() approach, but the overall structure is up to you. There may be cases in the life of that page which you don't want to bind, I don't know.

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279
0

There is maybe 2 possible reason cause it doesn't work 1st You're trying to bind event before 'span' is part of DOM Solution is bind event after this:

conntent.append('<div class="item"><span>' +data + '</span></div>');
$('span:last').bind('click', handler);

2nd maybe you should use context like this

$('span', conntent).bind('click',handler)

cheers :)