简体   繁体   中英

on.click not working after first click on dynamically created table

I dynamically create a table full of links of 'actors', which allows to pull the actors information into a form to delete or update the row. The delete button only pops up when you select an actor.

I'm able to click a row, pull the information into the forms, and delete it on first try. However when I attempt to add a new 'Actor' and then delete it, or just delete an existing 2nd row, the button 'Delete Actor' doesn't work. It's only after the first successful delete does the button no longer work.

var addActor = function() {
    // Creates a table of links for each added actor  with an id based from # of actors
    $("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this)' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");

    $(".update").off("click");
    $(".update").on("click", selectActor);
};


var deleteActor = function(e) {
    $("#deleteActor").on('click', function(event) {
        event.preventDefault();
        var row = e.parentNode.parentNode;
        row.parentNode.removeChild(row);
        clearForm(actorForm);
        actorState("new");
    });
};

I'm new to jQuery/javascript, and I'm pretty sure its due to the change in DOM, but I just don't know what to change to make it work.

Here is an Example of it in action

Try

var deleteActor = function(e) {

$("#deleteActor").unbind();
$("#deleteActor").on('click', function(event) {
    event.preventDefault();
    var row = e.parentNode.parentNode;
    row.parentNode.removeChild(row);
    clearForm(actorForm);
    actorState("new");
});

};

Here is the link for unbind. http://api.jquery.com/unbind/

The problem is because you're adding another click handler (in jQuery) within the click handler function run from the onclick attribute. You should use one method or the other, not both. To solve the problem in the simplest way, just remove the jQuery code from the deleteActor() function:

var deleteActor = function(e) {
    var row = e.parentNode.parentNode;
    row.parentNode.removeChild(row);
    clearForm(actorForm);
    actorState("new");
};

when you add html dynamically you need to attach the event to the parent static element like so:

$("#actorsTable").on("click","a.update", function() {
  $(this).closest("tr").remove();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM