Lawrence
Lawrence

Reputation: 727

Jquery remove element after append

So i was just wondering. Why does this work:

$("input[name='edit-meta']").keyup(function(e){
    if(e.keyCode=='32'||e.keyCode=='13'){
        var clicked=$(this);
        var tag=$(this).val();
        clicked.siblings("#edit-meta").append('<span style="background:<?php echo $ad_details_arr[9]?>;color:<?php echo $ad_details_arr[8]?>" class="tag">'+tag.slice(0,-1)+'<a href="#" class="remove" style="background:<?php echo $ad_details_arr[10]?>;color:<?php echo $ad_details_arr[8]?>;margin:5px">x</a></span>');
        clicked.val("");
    }
    $("a.remove").on("click",function(e){
        e.preventDefault();
        var clicked=$(this);
        clicked.closest("span.tag").fadeOut(function(){
            $(this).remove();
        });
    });
});

And not this:

$("input[name='edit-meta']").keyup(function(e){
    if(e.keyCode=='32'||e.keyCode=='13'){
        var clicked=$(this);
        var tag=$(this).val();
        clicked.siblings("#edit-meta").append('<span style="background:<?php echo $ad_details_arr[9]?>;color:<?php echo $ad_details_arr[8]?>" class="tag">'+tag.slice(0,-1)+'<a href="#" class="remove" style="background:<?php echo $ad_details_arr[10]?>;color:<?php echo $ad_details_arr[8]?>;margin:5px">x</a></span>');
        clicked.val("");
    }
});
$("a.remove").on("click",function(e){
    e.preventDefault();
    var clicked=$(this);
    clicked.closest("span.tag").fadeOut(function(){
        $(this).remove();
    });
});

I thought the .on would be sufficient to allow me to perform handlers yet created just like .live does.

Also stated in the jquery .on page.

" ... ability to handle events on descendant elements not yet created "

Upvotes: 0

Views: 2167

Answers (1)

pvnarula
pvnarula

Reputation: 2821

You can use this:-

$(document).on("click" , "a.remove" ,function(e){
    e.preventDefault();
    var clicked=$(this);
    clicked.closest("span.tag").fadeOut(function(){
        $(this).remove();
    });
});

The above thing will not work because a.remove is not available in the DOM.

The first example work because you are attaching event to a.remove after it is added to the DOM.

Upvotes: 6

Related Questions