当运行状况达到0时,该段落不变

时间:2019-02-09 22:27:14

标签: javascript if-statement

我不知道为什么'test'段落在达到0时没有改变。我该怎么做?我试图将“损坏”,“愈合”放入“如果陈述”中,但是没有用。条件很简单,所以我不知道出了什么问题。

而且,当健康状况小于0或大于100时,如何停止功能?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>SMTH</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="styles/styles.css" />
</head>
<body>
    <div class="main">
        <p id="health">Enemy's health: </p>
        <dl>
            <dd id="plus">+100</dd>
            <dd id="minus">-100</dd>
        </dl>
        <p id="test"></p>
    </div>
    <script src="script/app.js"></script>
</body>
</html>

let healthS = document.getElementById('health');
let plus = document.getElementById('plus');
let minus = document.getElementById('minus');

health = 100;

let damage = ()=>{
    health -= Math.floor(Math.random() * 15);
    healthS.innerHTML = "Enemy's health: " + health;
}

let heal = ()=>{
    health += Math.floor(Math.random() * 10);
    healthS.innerHTML = "Enemy's health: " + health;
}

minus.onclick = damage;
plus.onclick = heal;


if(health > 80){
    test.innerHTML = "Alive";
}else if(health <= 0){
    test.innerHTML = "Dead";
}

1 个答案:

答案 0 :(得分:0)

将if语句放入heal和Damage函数中。在功能之外,它们仅在文档加载时被调用一次。因此状态永远不会改变

let healthS = document.getElementById('health');
let plus = document.getElementById('plus');
let minus = document.getElementById('minus');

var health = 100;

let damage = () => {

  health -= Math.floor(Math.random() * 15);
  if(health<=0)
  {
  health=0;

  }
  healthS.innerHTML = "Enemy's health: " + health;
  
  if (health > 80) {
    test.innerHTML = "Alive";
  } else {
    test.innerHTML = "Dead";
  }
  
}

let heal = () => {
  health += Math.floor(Math.random() * 10);
  healthS.innerHTML = "Enemy's health: " + health;
  if (health > 80) {
    test.innerHTML = "Alive";
  } else {
    test.innerHTML = "Dead";
  }
}

minus.onclick = damage;
plus.onclick = heal;
if (health > 80) {
  test.innerHTML = "Alive";
} else {
  test.innerHTML = "Dead";
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>SMTH</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="styles/styles.css" />
</head>

<body>
  <div class="main">
    <p id="health">Enemy's health: </p>
    <dl>
      <dd id="plus">+100</dd>
      <dd id="minus">-100</dd>
    </dl>
    <p id="test"></p>
  </div>
  <script src="script/app.js"></script>
</body>

</html>