I'm new to this site and to programming in general and I'm a bit stuck on a school assignment.(我是这个网站的新手,也是一般编程的新手,我对学校的工作有些困惑。)
For reference here is my code I'm currently working on: Pastebin(供参考,这是我目前正在使用的代码: Pastebin)
function initChests(){
let gameChests = document.getElementById('chests');
for(let i = 0; i < 3; i++) {
let singleChest = document.createElement('img');
singleChest.src = 'images/chest-closed.png';
singleChest.alt = 'A chest'
singleChest.style.marginRight = '20px';
gameChests.appendChild(singleChest);
}
}
function initChestEventListeners() {
singleChest.addEventListener('click', chestClicked);
}
function chestClicked(e){
console.log("hello");
}
Now to my problem.(现在到我的问题。)
What I want to do is access the variable singleChest
in my initChestEventListeners
function without making the variable global.(我想要做的是在我的initChestEventListeners
函数中访问变量singleChest
而不使变量成为全局变量。)
I am aware I can just put the singleChest
addEventListener inside the initChests
function, but that's not quite what I want to do either.(我知道我可以将singleChest
addEventListener放在initChests
函数中,但这也不是我想要的。)
I want to make it work with the function structure I have if possible.(如果可能,我想使其与我拥有的功能结构一起使用。)
Is this something that is possible and if so, can someone please explain what I would need to do or redirect me to a guide that could help explain the solution?(这是否可行?如果可以,有人可以解释一下我需要做什么,或者将我重定向到可以帮助解释解决方案的指南吗?)
Thank you in advance!(先感谢您!)
Kind regards.(亲切的问候。)
ask by Ted Nilsson translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…