jQuery functions not responding after append()

后端 未结 3 1526
故里飘歌
故里飘歌 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:55

    Your code handles the click event for all elements currently in $('.remove').
    Any elements that do not exist yet are not affected.

    You need to call the .live() or .delegate methods, which will handle the event for all elements that match the selector, no matter when they were created.

    For example:

    $(".remove").live('click', function() {
        alert("removing");
        $(this).remove();
    });
    
    0 讨论(0)
  • 2020-12-19 04:55

    It's because when your code runs, the items aren't added yet. You need to add the remove click function to be dynamically assigned to your new block after you add it during the add click function.

    $(".add").click(function() {
      $("#targetbox").append("<span class='remove'>This element was added</span>");
      // Add code here for .remove click function
    });
    
    0 讨论(0)
  • 2020-12-19 04:57

    Add the click method directly to your newly appended element

    $(".add").click(function() {
        $("#targetbox").append("<span class='remove'>This element was added</span>")
        .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("<span class='remove'>This element was added</span>");
    });
    
    $(".remove").live("click", function() {
        alert("removing");
        $(this).remove();
    });
    
    0 讨论(0)
提交回复
热议问题