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

在javascript循环中创建唯一的Id按钮,javascript,Javascript,我需要创建一个填充有按钮的表。每个按钮必须具有唯一的id才能编辑其所在行中的值。我在单击时设置了一个显示按钮id的警报,但所有创建的按钮似乎都具有相同的id。我的代码有什么问题? 请帮忙,我是js的新手。我们将非常感谢您的帮助 这是我的代码: <!doctype html> <html> <head> <title>js table</title> <meta charset="utf-8" /> <meta htt

我需要创建一个填充有按钮的表。每个按钮必须具有唯一的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>

js表
老顶排

对于(var i=0;i更改您的客户端处理程序以引用单击的实际按钮。更改如下:

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

newButton.addEventListener("click", function(e) {
    alert("Button Id: " + this.id);
});
变量
newButton
for
循环中被反复使用,因此当任何
onclick
处理程序实际运行时,所有按钮都已创建,
newButton
将包含它曾经拥有的最后一个值

相反,您可以使用
this
引用已单击的元素,因此
this.id
将显示已单击按钮的id值


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

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

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

newButton.addEventListener("click", function(e) {
    alert("Button Id: " + this.id);
});
变量
newButton
for
循环中被反复使用,因此当任何
onclick
处理程序实际运行时,所有按钮都已创建,
newButton
将包含它曾经拥有的最后一个值

相反,您可以使用
this
引用已单击的元素,因此
this.id
将显示已单击按钮的id值


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

代码对我来说运行良好,按钮编号正确:所有按钮都分配了不同的id,您显示的值错误。请尝试警报(This.id)而不是newButton.id。代码对我来说运行正常,按钮编号正确:所有按钮都分配了不同的id,您显示的值错误。请尝试使用alert(this.id)而不是newButton.id。