Unable to remove dynamically added content with jQ

2019-08-10 06:13发布

问题:

I'm using jQuery to let users dynamically add and remove form fields, but it's not working properly.

It works perfectly fine when removing the first field (which is hard-coded in the HTML mark-up), but it won't let me remove any of the fields that have been added dynamically.

Here's my jQuery code:

$("#addDog").click(function(event)
{
    event.preventDefault();

    var doglist = <?php echo "'" . $javadogs . "'"; ?>;
    var newdog = '<div><select name="resDog[]" class="select">' + doglist + '</select><input type="text" class="shortinput" name="resResult[]" size="20" value="" /><a href="#" class="deleteDog"><img src="/admin/images/delete.png" alt="Remove dog" /></a></div>';
    $(this).parent().before(newdog);
});

$(".deleteDog").click(function(event)
{
    event.preventDefault();
    $(this).parent().remove();
});

I tried using jQuery's .on() function, but that didn't work either.

回答1:

Here's how you want to use on

$(document).on("click", ".deleteDog", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

Ideally all of these deleteDog buttons will be housed in some sort of container. If all of these buttons were to be in a div with an id of foo, you would more efficiently set up the events like this:

$("#foo").on("click", ".deleteDog", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

Now, instead of every click anywhere in the document being inspected, only those clicks that bubble up to #foo are.


I'm guessing you originally tried to use on like this:

$(".deleteDog").on("click", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

This is functionally identical to saying:

$(".deleteDog").bind("click", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

Omitting the selector parameter like this creates a directly-bound event—only the elements that match the .deleteDog selector at the time on is called will be wired.

Applying a selector—like in my original code—makes it a delegated event—jQuery will listen for all clicks, and if they originate from an element with the class deleteDog, the function will fire.