2017-04-16 5 views
0

は、ここに私のコードどのようにjavascriptでテーブル上のspesific行を削除するには? 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

投稿されたコードには2つの問題があります。

最初に、ボタン要素のonclick属性には関数オブジェクトが必要です。

(要素の開始タグ内にクリックハンドラを設定するためにHTMLで使用されるだけでHTMLパーサーによって解析され、そして純粋なJavaScriptで使用することはできないことでonclick="doSomething()"缶を設定します。)

第二: deleteRowメソッドは、テーブル内の行の現在のゼロベースのインデックスを使用しますが、クッキーまたは元のテーブル位置から取得された値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>

た場合を削除される行の値がnoであることを確認する必要があります。data-noのようなdata attribtueを設定して検査することをお勧めします。

関連する問題