在javascript循环中创建唯一的Id按钮
Creating unique Id buttons in a javascript loop
我需要创建一个用按钮填充的表。每个按钮都必须有一个唯一的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);
});
变量newButton
在for
循环中反复使用,因此当任何onclick
处理程序实际运行时,所有按钮都已创建,newButton
将包含它曾经拥有的最后一个值。
相反,您可以使用this
来引用被单击的元素,因此this.id
将是被单击按钮的id值。
注意:我还切换到使用.addEventListener()
,它还将事件数据结构传递给事件处理程序(在我的代码中显示为e
参数)。这通常是注册事件侦听器的更好方法,因为它允许多个侦听器,并允许您自动访问有关所发生事件的其他信息。
相关文章:
- 如何根据单击的按钮发送id参数
- JavaScript-onClick将按钮ID或单击按钮的文本传递给函数
- 传递来自<输入类型=“;文件“;id=“;文件“/>尽管还有一个按钮点击
- Jquery单击按钮上没有类或id的事件
- 我们可以设置属性'id'到不同的'按钮'通过使用javascript或jquery的循环
- jQuery:如何查找id是动态生成的单选按钮是否被选中
- Javascript尽管ID不同,但只有第一个按钮提交给Ajax表单
- 按下按钮时JqGrid会给出ID
- 如何使用顺序ID禁用多个单选按钮
- 在 PHP 生成的表中添加和访问按钮 ID
- 如何在jQuery的.on()方法中动态更新按钮的ID选择器
- 如何从按钮列表中获取按钮的 ID
- 单击按钮时,我如何将li的id添加为1
- 页面的类似facebook按钮的应用程序id
- 使用JQuery按钮更改URL#ID
- 如何选择并单击没有 id 属性的按钮
- 选中没有ID的单选按钮,只有名称、类型和值
- 在javascript循环中创建唯一的Id按钮
- 如何通过[id*=“按钮名称”]聚焦按钮
- 使用jQuery禁用动态id按钮