首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >数组问题中的addEventListener和值递减

数组问题中的addEventListener和值递减
EN

Stack Overflow用户
提问于 2019-02-22 05:58:40
回答 1查看 48关注 0票数 0

在数组中使用addEventListener时,我遇到了一个问题。我的目标是在每次点击后减少“敌人”的生命。添加一些代码进行解释:

代码语言:javascript
复制
var image;
var enemy = [];

function start()
{
  image = document.getElementById("image");
  
  enemy.push(new createEnemy());
  
  draw()
}

function draw()
{
  if(enemy[0].hp <= 0)  enemy.splice(0 , 1);  /*Also, will my splice work 
if instead of enemy[0] a "for loop" with (if(enemy[i].hp <= 0) enemy.splice(i, 1);) 
was used?*/

  requestAnimationFrame(draw);
}

function createEnemy()
{
  this.hp = 2;  //Value to be decreased
  this.image = document.getElementById("image");
  this.image.addEventListener("click", function()
    {
      console.log("Click works but hp doesn't decrease");
      this.hp--; //Problem cause
    })
}
代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <body onload="start()">
    <img id="image" src="https://i.imgur.com/hZWobCv.gif">
  </body>
</html>

此外,有没有比在动画帧中使用拼接更简单的方法来摧毁“敌人”,如果他们的生命值达到0?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-22 06:05:11

回调函数有自己的this,请使用已安装的箭头函数:

代码语言:javascript
复制
this.image.addEventListener("click", () =>
    {
      console.log("Click works but hp doesn't decrease");
      this.hp--; // will use the parent's this.hp
    })

代码语言:javascript
复制
var image;
var enemy = [];

function start() {
  image = document.getElementById("image");

  enemy.push(new createEnemy());

  draw()
}

function draw() {
  if (enemy[0].hp <= 0) enemy.splice(0, 1); //Also, will my splice work if instead of enemy[0] a "for loop" with (enemy[i], enemy.splice(i, 1);) was used?

  requestAnimationFrame(draw);
}

function createEnemy() {
  this.hp = 10; //Value to be decreased
  this.image = document.getElementById("image");
  this.image.addEventListener("click", () => {
    console.log("Click works , this.hp = ", this.hp);
    this.hp--; 
  })
}
代码语言:javascript
复制
<!DOCTYPE html>
<html>

<body onload="start()">
  <img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>

</html>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54816862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档