在创建时如何将onclick设置为动态按钮并与正确的索引相对应

问题描述 投票:0回答:1

所以我有一个简单的问题,我动态创建的按钮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>
javascript php html button dynamic
1个回答
0
投票

一个简单的解决方法如下

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'立即解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.