javascript - 为什么只有数组中的最后一个对象可用
问题描述
我想访问我创建的所有按钮,但我只能访问最后一个。第一个 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
}
}
}
}
解决方案
推荐阅读
- c# - HttpGetAttribute 不包含采用 1 个参数的构造函数
- sql - 数据应该采用哪种格式才能使用 RJDBC 成功地将其插入到 Netezza DB 中的表中
- mysql - 如何根据 2 个标准获取记录
- angular - Angular 2 - ngIf Alternative 它不会在 ngIf 值更改时初始化组件
- android - 如何使用意图以语法方式从谷歌驱动器、android中的下拉框存储应用程序获取文件内容
- php - 日期范围切片
- jquery - 在 jquery ajax 调用之后,data-src 没有被 src 替换
- javascript - 在页面其他位置激活 Bootstrap 4 下拉菜单
- javascript - javascript中使用的这种语法在哪里(function(){}())
- android - Flutter - 如何在 android 中自动启用位置服务?