首页 > 解决方案 > 为什么只有数组中的最后一个对象可用

问题描述

我想访问我创建的所有按钮,但我只能访问最后一个。第一个 console.log() (nr1),给了我我按下的所有按钮的 textContent。但是最后一个 console.log() 仅与最后一个按钮/文本内容(数组中的最后一个对象)一起“工作”(或给我)。

            opt.onclick = function(){

                for(item of arr){

                    let btn = document.createElement('button')
                    let btnText = document.createTextNode(item.name)
                    btn.appendChild(btnText)
                    forum.appendChild(btn)

                    btn.onclick = function(){
                        console.log(btn.textContent) //Nr.1
                        if(btn.textContent === item.name){
                            console.log(item.name) //Nr.2
                        }
                    }



                }

            }

标签: javascript

解决方案


推荐阅读