今天我学习了如何使用 JS 创建和监听按钮之类的对象。然后一个问题发生了。
在 shopDraw() (创建按钮)并试图从另一个函数中使用 shopClose() 杀死它们之后,我得到错误:“ReferenceError:button1 未定义”。我试过从 shopDraw() 做同样的事情,但它也返回错误。我究竟做错了什么?
如果我尝试在警报后将代码从 shopClose() 粘贴到 shopDraw() ,它很容易擦除它们!
function shopDraw() {
shopOpened=true;
var br1 = document.createElement('br');
var br2 = document.createElement('br');
var br3 = document.createElement('br');
var button1 = document.createElement('input');
button1.type = 'button';
if (swordBought===false) {button1.value = 'Приобрести меч '; swordBought=true;}
else {button1.value='Улучшить меч'}
button1.addEventListener('click', function() {shop(1)}, false);
var button2 = document.createElement('input');
button2.type = 'button';
if (armorBought===false) {button2.value = 'Приобрести броню '; armorBought=true;}
else {button2.value='Улучшить броню'}
button2.addEventListener('click', function() {shop(2)}, false);
var button3 = document.createElement('input');
button3.type = 'button';
if (bootBought===false) {button3.value = 'Приобрести сапоги '; bootBought=true;}
else {button3.value='Улучшить сапоги'}
button3.addEventListener('click', function() {shop(3)}, false);
var button4 = document.createElement('input');
button4.type = 'button';
button4.value='Восстановить здоровье'
button4.addEventListener('click', function() {shop(4)}, false);
document.body.insertBefore(button1, BattleLogger);
document.body.insertBefore(button2, BattleLogger);
document.body.insertBefore(br1, button2);
document.body.insertBefore(button3, BattleLogger);
document.body.insertBefore(br2, button3);
document.body.insertBefore(button4, BattleLogger);
document.body.insertBefore(br3, button4);}
function shopClose(){
button1.parentNode.removeChild(button1);
button2.parentNode.removeChild(button2);
button3.parentNode.removeChild(button3);
button4.parentNode.removeChild(button4);
br1.parentNode.removeChild(br1);
br2.parentNode.removeChild(br2);
br3.parentNode.removeChild(br3);