所以我有一个简单的问题,我动态创建的按钮onclick事件似乎只引用最后一个索引。在我的for循环中,如果使用i,则会出现错误“未捕获的TypeError:无法读取未定义的属性'setAttribute'”。如果我输入5之类的索引,我将获得正确的按钮。我确信这是我忽略的事情,在这里我引用了其他文档也没有运气。
<html>
<body>
<div id="numbers"></div>
<?php
$read = file('numbers.txt');?>
<script>
var rest = '<?php echo json_encode($read[0]); ?>'
rest = String(rest).replace('"','').replace('"','')
rest = rest.split(',')
console.log(rest)
for(i=0;i<rest.length;i++){
var btn = document.createElement("BUTTON");
var t = document.createTextNode(rest[i]);
btn.id = "but"+String(i);
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener("click", function test(){
btn[i].setAttribute("style","color:green;font-size:23px");
});
}
</script>
</body>
</html>
***其他示例
<html>
<body>
<div id="numbers"></div>
<?php
$read = file('numbers.txt');?>
<script>
var rest = '<?php echo json_encode($read[0]); ?>'
rest = String(rest).replace('"','').replace('"','')
rest = rest.split(',')
console.log(rest)
for(i=0;i<rest.length;i++){
var btn = document.createElement("BUTTON");
var t = document.createTextNode(rest[i]);
btn.id = "but"+String(i);
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.onclick = function test(){
document.getElementsByTagName('button')[i].setAttribute("style","color:green;font-size:23px");
}
}
</script>
</body>
</html>
一个简单的解决方法如下
btn.addEventListener("click", function test(){
this.setAttribute("style","color:green;font-size:23px");
});
做类似---的问题>
btn.setAttribute("style","color:green;font-size:23px");
或
document.getElementsByTagName('button')[i].setAttribute("style","color:green;font-size:23px");
是在添加事件侦听器时,不会立即执行功能,而是在用户单击按钮时执行这些功能,此时循环已完成执行,并且'i'和'btn'均指最后一个按钮已创建。
因此使用'this'立即解决了问题。