2016-06-28 103 views
1

我试图删除动态创建的表行,当用户单击该表行的一部分删除按钮。但这似乎不适合我。我尝试了许多不同的方法,但它仍然从第一个创建的行中删除,或者根本不删除。这是我目前掌握的并且不起作用。删除动态创建的表行按钮单击

JS功能:

var rowID=0; 
var table = document.createElement('table'); 
table.id = "attrtable"; 
table.className = "attrtable"; 

function showAttributes() 
{ 
    var tr = document.createElement('tr'); 
    tr.id=rowID; 
    var attributeName = document.getElementById("attNam").value; 
    var choice=document.getElementById("attrTypefromCombo"); 
    var attrTypeCombo = choice.options[choice.selectedIndex].text; 

    showAttrDivision.appendChild(attrName); 
    showAttrDivision.appendChild(attrType); 
    showAttrDivision.appendChild(closeattr); 

    var tdAttrName = document.createElement('td'); 
    var tdAttrType = document.createElement('td'); 
    var tdDelete = document.createElement('td'); 

    var text1 = document.createTextNode(attributeName); 
    var text2 = document.createTextNode(attrTypeCombo); 
    var deletebtn = document.createElement("button"); 
    deletebtn.type="button"; 
    //deletebtn.id = rowID; 
    var text3= "<img src='../Images/Delete.png'>"; 
    deletebtn.innerHTML = text3; 
    deletebtn.onclick = function() { 
     deleteRow(rowID); 
    }; 



    tdAttrName.appendChild(text1); 
    tdAttrType.appendChild(text2); 
    tdDelete.appendChild(deletebtn); 
    tr.appendChild(tdAttrName); 
    tr.appendChild(tdAttrType); 
    tr.appendChild(tdDelete); 
    rowID++; 
    table.appendChild(tr); 
    showAttrDivision.appendChild(table); 
} 

function deleteRow(row) 
{ 
    document.getElementById("attrtable").deleteRow(row); 
} 

回答

1
function deleteRow(row) 
{ 
    var i=row.parentNode.parentNode.rowIndex; 
    document.getElementById('POITable').deleteRow(i); 
} 


function insRow() 
{ 
    var x=document.getElementById('POITable'); 
     // deep clone the targeted row 
    var new_row = x.rows[1].cloneNode(true); 
     // get the total number of rows 
    var len = x.rows.length; 
     // set the innerHTML of the first row 
    new_row.cells[0].innerHTML = len; 

     // grab the input from the first cell and update its ID and value 
    var inp1 = new_row.cells[1].getElementsByTagName('input')[0]; 
    inp1.id += len; 
    inp1.value = ''; 

     // grab the input from the first cell and update its ID and value 
    var inp2 = new_row.cells[2].getElementsByTagName('input')[0]; 
    inp2.id += len; 
    inp2.value = ''; 

     // append the new row to the table 
    x.appendChild(new_row); 
} 
使用 .live绑定你的事件将自动绑定它时动态添加的行

Demo_click here

+0

谢谢。有我的工作使用这个指导方针 –

0

更改删除线,因为你的表名是 “attrtable” 而不是 “表”。

document.getElementById("attrtable").deleteRow(row); 
+0

对不起'布特那。这是一个错字。但它仍然不起作用 –

0
$(buttonSelector).live ('click', function() 
{ 
    $(this).closest ('tr').remove(); 
} 
); 

编辑

live现在已经过时,因为1.7版本,我认为。

现在要走的路是用on代替live

$('#tableid').on('click', buttonSelector, function(){ 
    $(this).closest ('tr').remove(); 
}); 

查看doc

Reference