简体   繁体   中英

Deleting dynamically created table rows

I am trying following function to create table rows and delete them onclick function, following is what I tried:

function CreateDelete()
{

            var table = document.getElementById('newbook');
            var tableBody = document.createElement('tbody');
            var row, columnUserId, columnCountingAreaID, columnDeleteRec;


            row = document.createElement('tr');
            columnUserId = document.createElement('td');
            columnUserId.appendChild(document.createTextNode("hi"));

            columnCountingAreaID = document.createElement('td');
            columnCountingAreaID.appendChild(document.createTextNode("there"));

            columnDeleteRec = document.createElement('td');
            var element = document.createElement("input");
            //Assign different attributes to the element. 
            element.setAttribute('type','button');
            element.setAttribute('name','X');
            element.setAttribute('value','X');               

            element.onclick = function() { 
                $('#newbook input[type="button"]').click    (function () {
 $(this).closest('tr').remove();});
            };

            row.appendChild(columnUserId);
            row.appendChild(columnCountingAreaID);
            columnDeleteRec.appendChild(element);
            row.appendChild(columnDeleteRec);

            tableBody.appendChild(row);
            table.appendChild(tableBody);
}

The problem is its not deleting the row onclick operation. Can anybody tell whats wrong being done here.

you are binding event when row clicked

$('#newbook input[type="button"]').click(function () {
 $(this).closest('tr').remove();
});

this should at the end of your code and remove the binding event with element.onclick

You just need to change the onclick handler to this:

element.onclick = 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