2016-04-10 4 views
0

ボタンを挿入したテーブルを作成する必要があります。行内の値を編集するには、各ボタンに固有のIDが必要です。私はクリック時にボタンのIDを表示するアラートを設定しましたが、作成されたすべてのボタンは同じIDを持つようです。私のコードに何が問題なのですか? plz help、本当にjsの初心者です。どんな助力も高く評価されます。javascriptループ内でユニークなIdボタンを作成

<!doctype html> 
<html> 
<head> 
<title>js table</title> 

<meta charset="utf-8" /> 
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1" /> 
</head> 


<body> 

<table id="TableA" dir="ltr" width="500" border="1"> 
<tr> 
<td>Old top row</td> 
</tr> 
</table> 

</body> 

<script type="text/javascript" > 


for (var i = 0; i<6; i++) { 

    // Get a reference to the table 
    var tableRef = document.getElementById("TableA"); 

    // Insert a row in the table at row index 0 
    var newRow = tableRef.insertRow(0); 

    // Insert a cell in the row at index 0 
    var boton = newRow.insertCell(0); 

    // Append a text node to the cell 
    var newButton = document.createElement("BUTTON"); 
    newButton.id = i; 

    newButton.innerHTML = "Unique id button"; 
    boton.appendChild(newButton); 


    // Insert a cell in the row at index 0 
    var newCell = newRow.insertCell(0); 

    // Append a text node to the cell 
    var newText = document.createElement("P"); 
    newText.innerHTML = "item" +" "+ i; 
    newCell.appendChild(newText); 

    newButton.onclick = function(){ 
    alert("Button Id: " + newButton.id); 
    } 


} 

</script> 
+0

コードは正常に動作し、ボタンの番号は正しく表示されます。https://jsfiddle.net/btemdopw/ –

+0

すべてのボタンには異なるIDが割り当てられていますが、値が間違って表示されています。 newButton.idではなくalert(this.id)を試してください。 –

答えて

3

変更クリックされた実際のボタンを参照するために、あなたのクライアントハンドラ:

が、これは私のコードです。これに

newButton.onclick = function(){ 
    alert("Button Id: " + newButton.id); 
} 

:このからの変更

newButton.addEventListener("click", function(e) { 
    alert("Button Id: " + this.id); 
}); 

変数newButtonがあなたのonclickハンドラのいずれかの実際の実行時間によってのでごforループ内で何度も使用されている、すべてのボタンを持っていますnewButtonには最後の価値が含まれます。

代わりに、thisをクリックして、クリックされた要素を参照することができます。this.idは、クリックされたボタンのid値です。

注:.addEventListener()も使用して、イベントハンドラにイベントデータ構造を渡します(コードではe引数として表示されます)。これは、複数のリスナーを許可し、発生したイベントに関する他の情報に自動的にアクセスできるようにするため、イベントリスナーを登録する一般的に良い方法です。

+0

ここにあなたの例があります:https://plnkr.co/edit/tEdn36zVIeSDenIBdOgR?p=preview –

関連する問題