0

my code:

$(".test1").children().click(function(){
    $(".test2").append('<span>something</span>');           
});

$(".test2").children().on('click', function(){
    alert("done");      
});

the span with "something" should be the last child of test2 after clicking children of test1. is my append done right? is the click event on test2 done correctly?

thx!

BigX_Jazz
  • 103
  • 3
  • 13

2 Answers2

1

this works:

$(".test1").children().click(function(){
    $(".test2").append('<span> something</span>');           
});

$(".test2").on('click', 'span', function(){
    alert("done");      
});

live demo

mychalvlcek
  • 3,956
  • 1
  • 19
  • 34
  • thx, this works!, but is there a way to let the click trigger even if the child of test2 is not a span? – BigX_Jazz Feb 17 '13 at 14:41
0

ok just a little explanation about your append, your append is just right but your attaching click events to $(".test2").children() before the new child is appended (test1 is clicked). so the click event is never attached to the span.

srosh
  • 124
  • 1
  • 3
  • i click test2 jsut after i clicked test1 – BigX_Jazz Feb 17 '13 at 14:42
  • yeah but in this case you're assigning event handlers before you're clicking. you see the new child is not there when event handlers are assigned. `.children()` means children at that point in time. this is why `$(".test2").on` works, handler is set on the parent and `'span'` is the filter so if you want to make it work for something other than a span you should change the filter. – srosh Feb 17 '13 at 19:34