ボタンを挿入したテーブルを作成する必要があります。行内の値を編集するには、各ボタンに固有の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>
コードは正常に動作し、ボタンの番号は正しく表示されます。https://jsfiddle.net/btemdopw/ –
すべてのボタンには異なるIDが割り当てられていますが、値が間違って表示されています。 newButton.idではなくalert(this.id)を試してください。 –