在javascript循环中创建唯一的Id按钮

Creating unique Id buttons in a javascript loop

本文关键字:Id 按钮 唯一 创建 javascript 循环      更新时间:2024-05-01

我需要创建一个用按钮填充的表。每个按钮都必须有一个唯一的id才能编辑其行中的值。我在点击时设置了一个警报显示按钮的id,但所有创建的按钮似乎都有相同的id。我的代码出了什么问题?请帮帮我,我真的是js新手。如有任何帮助,我们将不胜感激。

这是我的代码:

<!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>

更改客户端处理程序以引用实际单击的按钮。更改:

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

到此:

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

变量newButtonfor循环中反复使用,因此当任何onclick处理程序实际运行时,所有按钮都已创建,newButton将包含它曾经拥有的最后一个值。

相反,您可以使用this来引用被单击的元素,因此this.id将是被单击按钮的id值。

注意:我还切换到使用.addEventListener(),它还将事件数据结构传递给事件处理程序(在我的代码中显示为e参数)。这通常是注册事件侦听器的更好方法,因为它允许多个侦听器,并允许您自动访问有关所发生事件的其他信息。