我试图在不同的函数中调用两次函数。第一个函数创建两个按钮并添加onclick
事件。我需要多次这样做,但它不起作用!这是我的Javascript:
// PLAYER INFO
var playerHP = 100;
var playerAt = 10;
var playerDef = 0;
var gold = 0;
//ENEMY FROG INFO
var enemy = 'FROG';
var enemyHP = 50;
var enemyAt = 5;
var loot = 5;
//FOF
function fof() {
var fight = document.createElement("BUTTON");
var t = document.createTextNode("FIGHT!");
fight.appendChild(t);
fight.id='attack';
document.body.appendChild(fight);
document.getElementById('attack').addEventListener('click', attack);
var or = document.createElement("P");
var g = document.createTextNode("or");
or.appendChild(g);
document.body.appendChild(or);
var flee = document.createElement("BUTTON");
var p = document.createTextNode("FLEE!");
flee.appendChild(p);
flee.id = 'flee';
document.body.appendChild(flee);
document.getElementById('playerflee').addEventListener('click', flee);
}
//ENEMY ATTACK
function enemyAttack() {
playerHP = playerHP - enemyAt;
var enemyFight = document.createElement('P');
var t = document.createTextNode('The enemy attacked you! You now have '+ playerHP + ' HP left!');
enemyFight.appendChild(t);
enemyFight.id = 'enemyattack';
document.body.appendChild(enemyFight);
fof();
}
//FIGHT
function attack() {
enemyHP = enemyHP - playerAt;
var playerAttack = document.createElement('P');
var t = document.createTextNode('You attacked the enemy! It has ' + enemyHP + ' HP left!');
playerAttack.appendChild(t);
playerAttack.id = 'attack';
document.body.appendChild(playerAttack);
enemyAttack();
}
//FLEE
function flee() {
var spare = document.createElement('P');
var t = document.createTextNode('You ran away! You gained 0 loot!');
spare.appendChild(t);
spare.id = 'playerflee';
document.body.appendChild(spare);
}
//Enemy Spawn
function spawn(){
var p = document.createElement("P");
var t = document.createTextNode("A wild FROG appeared! He has " + enemyHP + ' HP and ' + enemyAt+ ' attack! Will you...');
p.appendChild(t);
document.body.appendChild(p);
fof();
}
正如您所看到的,我在fof()
进行了两次spawn()
,在enemyAttack()
进行了一次。我知道它在第一个工作,因为它在我第一次调用时工作。但是,当我来到第二个enemyAttack()
时,它不起作用!任何帮助将不胜感激。
此外,我的HTML只是一个调用onclick
spawn()
事件的按钮
答案 0 :(得分:2)
ID是唯一的,您只能在文档中使用任何给定ID的单个元素。知道了这一点,document.getElementById('attack')
每次只返回DOM中的第一个元素。
由于您已经拥有该元素,因此无需查找
function fof() {
var fight = document.createElement("BUTTON");
var t = document.createTextNode("FIGHT!");
fight.className = 'attack';
fight.addEventListener('click', attack);
fight.appendChild(t);
document.body.appendChild(fight);
...