Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - jQuery functions not responding after append()

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 bound to that element will not respond. Here's roughly what my code looks like:

$(".add").click(function() {
$("#targetbox").append("<span class='remove'>This element was added</span>");
});

$(".remove").click(function() {
alert("removing");
$(this).remove();
});

If I pre-populate #targetbox with items, they respond to the click function. It's only the items that are dynamically added that do not respond to the function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...