2011-05-21 108 views

回答

4

刪除元素最好使用DOM節點函數完成,如removeChild,而不是innerHTML-黑客。例如:

function removeAllRowsContainingCheckedCheckbox(table) { 
    for (var rowi= table.rows.length; rowi-->0;) { 
     var row= table.rows[rowi]; 
     var inputs= row.getElementsByTagName('input'); 
     for (var inputi= inputs.length; inputi-->0;) { 
      var input= inputs[inputi]; 

      if (input.type==='checkbox' && input.checked) { 
       row.parentNode.removeChild(row); 
       break; 
      } 
     } 
    } 
} 
2

下面是關於如何可以這樣做一個小的樣機:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
     "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>Mockup</title> 
<script type="text/javascript"> 
function killRow(src) { 
    var dRow = src.parentElement.parentElement; 
    document.all("table").deleteRow(dRow.rowIndex); 
} 
</script> 
</head> 
<body> 

<form action="something.html"> 
<table id="table"> 
    <tr> 
     <td><input type='checkbox' onclick='killRow(this);'>Click me!</td> 
     <td>Demodata 1</td> 
    </tr> 
    <tr> 
     <td><input type='checkbox' onclick='killRow(this);'>Click me!</td> 
     <td>Demodata 2</td> 
    </tr> 
</table> 
</form> 

</body> 
</html> 

鍵入這是一個JScript函數,然後可以從任何行中有使用。它甚至可能更普遍化。當點擊複選框時,該函數被調用。

我寧可不使用innerHTML,我更喜歡DOM節點(這裏是parentElement)。

2

這是一個通過檢查複選框的值來執行刪除行所需操作的功能。在刪除按鈕的onclick事件中調用此函數(包含註釋)。希望這有助於:)

function removeSampleRow(id) { 
    /***We get the table object based on given id ***/ 
    var objTable = document.getElementById(id); 

    /*** Get the current row length ***/ 
    var iRow = objTable.rows.length; 

    /*** Initial row counter ***/ 
    var counter = 0; 

    /*** Performing a loop inside the table ***/ 
    if (objTable.rows.length > 1) { 
     for (var i = 0; i < objTable.rows.length; i++) { 

      /*** Get checkbox object ***/ 
      var chk = objTable.rows[i].cells[0].childNodes[0]; 
      if (chk.checked) { 
       /*** if checked we del ***/ 
       objTable.deleteRow(i); 
       iRow--; 
       i--; 
       counter = counter + 1; 
      } 
     } 

     /*** Alert user if there is now row is selected to be deleted ***/ 
     if (counter == 0) { 
      alert("Please select the row that you want to delete."); 
     } 
    }else{ 
     /*** Alert user if there are no rows being added ***/ 
     alert("There are no rows being added"); 
    } 
}