2012-01-23 36 views
1

我使用的Greasemonkey腳本,並更新使用下面的代碼表。我附上了桌子的圖像。但是當我點擊刪除時,rowIndex爲所有行返回-1。我不明白爲什麼它返回-1。的rowIndex是返回-1

table = document.getElementById('keys-table'); 
if (!table) return; 
table.innerHTML = ''; 


// header 
row = document.createElement('tr'); 
th = document.createElement('th'); 
th.innerHTML = "Group"; row.appendChild(th); 
th = document.createElement('th'); 
th.innerHTML = "Key"; row.appendChild(th); 
th = document.createElement('th'); 
th.innerHTML = " "; row.appendChild(th); 
table.appendChild(row); 

// keys 
for (i = 0 ; i < keys.length ; i++) { 
    row = document.createElement('tr'); 
    td = document.createElement('td'); 
    td.innerHTML = keys[i][0]; 
    row.appendChild(td); 
    td = document.createElement('td'); 
    td.innerHTML = keys[i][1]; 
    row.appendChild(td); 
    td = document.createElement('td'); 

    button = document.createElement('input'); 
    button.type = 'button'; 
    button.value = 'Delete'; 
    button.addEventListener("click", function(event) { 
      DeleteKey(event.target.parentNode.parentNode.rowIndex,event.target); 
     }, false); 
    td.appendChild(button); 
    row.appendChild(td); 

    table.appendChild(row); 
} 

enter image description here

回答

4

tr元件要在一個<tbody>元件。

通常情況下,瀏覽器插入一個自動的,但如果它沒有,你有...

table.innerHTML = ''; 

消滅它如果您確保原始表有<tbody>,然後做.. 。

table = document.getElementById('keys-table'); 
if (!table) return; 

var tbody = table.tBodies[0]; 
tbody.innerHTML = ''; 

...然後追加行tbody,它會工作。


附註,但我個人建議使用DOM方法刪除舊行而不是innerHTML

var tbody = table.tBodies[0]; 
while(tbody.firstChild) 
    tbody.removeChild(tbody.firstChild); 

var tbody = table.tBodies[0]; 
while(tbody.rows[0]) 
    tbody.deleteRow(tbody.rows[0]); 

似乎更合適。

2

好問題,並回答「我不是我」是正確的,一定要一個TBODY你行追加到您的表,然後附加到這個TBODY。