2017-04-16 43 views
0

這是我的代碼如何用javascript刪除表上的特定行?使用使用document.createElement()

function AddItemOnTable(){ 
     if(getCookie("no") == null){ 
      var no = 1; 
     }else if(parseInt(getCookie("no")) > 0){ 
      var no = getCookie("no"); 
     }else{ 
      var no = 1; 
     } 

     var tableRef = 
     document.getElementById('whatToBuy').getElementsByTagName('tbody')[0]; 
     var newRow = tableRef.insertRow(tableRef.rows.length);// Nambahin row di 
     tabel diurutan terakhir 

     var cell_no = newRow.insertCell(0);// Tambah row pada index yang ke 0 
     var newText = document.createTextNode(String(no));// Memberikan text 
     cell_no.appendChild(newText); 
     no = String(parseInt(no) + 1); 
     document.cookie = "no="+no; 

     var cell_btn = newRow.insertCell(7); 
     var input = document.createElement("input"); 
     input.type = "button"; 
     input.className = "button"; 
     input.value = "x"; 
     var index = parseInt(no-2); 
     //alert(index); 
     input.onclick = "DeleteRow(index)"; 
     cell_btn.appendChild(input); 
} 
function DeleteRow(no){ 
    document.getElementById("whatToBuy").deleteRow(no); 
    alert("a"); 
} 

:input.onclick = 「DeleteRow(索引)」;

爲什麼它不會調用「刪除行」功能? 對不起我的英語不好,即時通訊新的網頁開發:D

回答

1

發佈的代碼有兩個問題。

第一項:按鈕元素的onclick屬性需要一個函數對象。

(設置onclick="doSomething()"可以在HTML通過用來設置一個元素的開始標籤中點擊處理程序,但只能由HTML解析器解析,並且不能在純JavaScript中使用。)

二: deleteRow方法使用表中該行的當前從零開始的索引,但正在傳遞一個參數,該參數旨在成爲從cookie或原始表格位置獲取的no值。

該解決方案在這裏建議是使用相同的DeleteRow功能適用於所有的行,但要修改它來尋找按鈕的當前行的位置點擊:

var no = 100; // testing 
 
var table = document.getElementById("whatToBuy"); 
 

 
function addRows() { // testing 
 
    for(var i = 0; i < 5; ++i) { 
 
     var button = document.createElement("BUTTON"); 
 
     button.type = "button"; 
 
     button.textContent = "delete index " + no; 
 
     button.onclick = DeleteRow; 
 

 
     var row = document.createElement("TR"); 
 
     var cell = document.createElement("TD"); 
 
     cell.appendChild(button); 
 
     row.appendChild(cell); 
 
     table.appendChild(row); 
 

 
     ++no; 
 
    } 
 
} 
 

 
function DeleteRow() { 
 
    // find row to delete; 
 

 
    for(var row = this; row=row.parentNode;) { 
 
     if(row.tagName == "TR") { 
 
      break; 
 
     } 
 
    } 
 
    var rows = table.querySelectorAll("TR"); 
 
    for(var i = 0; i < rows.length; ++i) { 
 
     if(rows[i] === row) { 
 
      table.deleteRow(i); 
 
      break; 
 
     } 
 
    } 
 
}
<table id="whatToBuy"> 
 
</table> 
 
<button type="button" onclick="addRows()">add some rows</button>

如果需要確定被刪除行的值,我建議在行元素上設置和檢查data attribtue,如data-no

相關問題