jQuery functions not responding after append()

后端 未结 3 1527
故里飘歌
故里飘歌 2020-12-19 04:47

I\'m creating a series of div boxes that lets users add/remove items from each box with jQuery. I find that after I add a new element to a box, the click function I have bou

3条回答
  •  粉色の甜心
    2020-12-19 04:57

    Add the click method directly to your newly appended element

    $(".add").click(function() {
        $("#targetbox").append("This element was added")
        .bind("click",function(e) {
            alert("removing");
            $(this).remove();
        });
    });
    

    Or use the .live() method that will bind the click event for you after appending any new .remove elements

    $(".add").click(function() {
        $("#targetbox").append("This element was added");
    });
    
    $(".remove").live("click", function() {
        alert("removing");
        $(this).remove();
    });
    

提交回复
热议问题