Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add listener to appended content

I have some jQuery code like this:

$("#add").click(function(event){
    $("#list").append('<a class="remove" href="#">x</a>');

    return false;
});

$('.remove').live('click', function(){
    alert("123");
});

If one clicked on class=remove I would like it to alert 123. This doesn't happen though. I think this is a simple idea but I must be missing something.

Any ideas?

Thanks.

like image 813
Mr Goobri Avatar asked Feb 12 '13 13:02

Mr Goobri


2 Answers

Live is deprecated, use on

$(document).on('click','.remove',function(){
alert("123");
});
like image 146
Anton Avatar answered Sep 18 '22 23:09

Anton


Another way to add element and bind event without delegation:

$("#add").click(function(event){
    $("<a />", {
        "class": "remove",
        href: "#",
        text: "x"
    }).on("click", function() {
        alert("123");
        return false;
    }).appendTo("#list");

    return false;
});

Avoid using live method, since it was deprecated and finally removed in the last version of jQuery.

like image 22
VisioN Avatar answered Sep 18 '22 23:09

VisioN