简体   繁体   English

删除动态创建的表行

[英]Deleting dynamically created table rows

I am trying following function to create table rows and delete them onclick function, following is what I tried: 我正在尝试以下函数来创建表行并将其删除onclick函数,以下是我尝试的操作:

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. 问题是它没有删除行onclick操作。 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 这应该在代码的末尾,并使用element.onclick删除绑定事件

You just need to change the onclick handler to this: 您只需要将onclick处理程序更改为此:

element.onclick = function() {                   
    $(this).closest('tr').remove();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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