Javascript 如何在创建时将onclick设置为动态按钮,并与正确的索引相对应
所以我有一个简单的问题,我的按钮onclick事件是动态创建的,看起来只是引用最后一个索引。在for循环中,如果使用I,则会得到错误uncaughttypeerror:cannotread undefine的属性“setAttribute”。如果我输入像5这样的索引,我将得到正确的按钮。我确信这是我忽略了的事情,我引用了其他文件,但没有运气Javascript 如何在创建时将onclick设置为动态按钮,并与正确的索引相对应,javascript,php,html,button,dynamic,Javascript,Php,Html,Button,Dynamic,所以我有一个简单的问题,我的按钮onclick事件是动态创建的,看起来只是引用最后一个索引。在for循环中,如果使用I,则会得到错误uncaughttypeerror:cannotread undefine的属性“setAttribute”。如果我输入像5这样的索引,我将得到正确的按钮。我确信这是我忽略了的事情,我引用了其他文件,但没有运气 <html> <body> <div id="numbers"></div> <?php $read
<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");
或
在添加事件侦听器时,函数不会立即执行,而是在用户单击按钮时执行,此时循环已完成执行,“i”和“btn”都指最后创建的按钮
因此,使用“this”立即解决了问题。是的,它解决了,谢谢!!!我做了btn.addEventListener'click',函数绑定{返回函数{document.getElementsByTagName'button'[bound_I]。setAttributestyle,颜色:绿色;字体大小:23px;console.logbound_I}}I;这是可行的,但你的方式是少代码。
document.getElementsByTagName('button')[i].setAttribute("style","color:green;font-size:23px");