删除动态创建的表行

时间:2013-07-29 06:12:15

标签: javascript html html-table onclick

我正在尝试使用以下函数来创建表行并删除它们的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);
}

问题是它没有删除行onclick操作。 任何人都可以告诉我们这里做错了什么。

2 个答案:

答案 0 :(得分:0)

点击行时你是绑定事件

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

这应该在代码的末尾,并使用element.onclick

删除绑定事件

答案 1 :(得分:0)

您只需将onclick处理程序更改为:

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