首页 > 解决方案 > 在 Javascript 中访问函数中的变量

问题描述

我想检查 woodCount 变量是否等于或大于 25 我想在页面上显示一个新按钮。现在我只知道console.log true 或false。

对不起,如果这真的很容易或没有意义,但我是 Javascript 新手。谢谢!

JAVASCRIPT 文件

var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");



gatherWood.onclick = function(){
  woodCount++;
  wood.innerHTML = woodCount;
}


function fire() {
    if woodCount >= 25 {
       console.log('True');
  }else{
    console.log('False');
  }
}

文件

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Game</title>
  <meta name="description" content="Game">
  <meta name="author" content="SitePoint">
  <script src="game.js"></script>
  <link rel="stylesheet" href="style.css">

</head>

<body>
    <div>
    <input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
   Wood = <span id="wood">0</span> 
    </div>

</body>
</html>

标签: javascripthtmlcss

解决方案


  1. 向 DOM 添加一个按钮并将其隐藏。当它超过阈值时,将显示属性从隐藏切换到阻止。
  2. 确保我们在发生增量的 onclick 事件处理程序中调用样式切换发生的函数。

var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");

gatherWood.onclick = function() {
  woodCount++;
  wood.innerHTML = woodCount;
  fire();
};

function fire() {
  if (woodCount >= 25) {
    document.getElementById("higherThan25")
      .style.display = "block";
  } else {
    //console.log("False");
  }
}
.woodbtn {
  border-style: solid;
  border-color: white;
  color: white;
  padding: 10px 10px;
  text-align: center;
  font-size: 13px;
  cursor: pointer;
  float: right;
  background-color: transparent;
}

.woodtxt {
  text-color: white;
}

body {
  background-color: black;
  color: white;
}
<!doctype html>

<html lang="en">

<head>
  <meta charset="utf-8">

  <title>Game</title>
  <meta name="description" content="Game">
  <meta name="author" content="SitePoint">
  <script src="game.js"></script>
  <link rel="stylesheet" href="style.css">

</head>

<body>
  <div>
    <input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
    <input style="display: none;" class="woodbtn" type="button" value="Higher Than 25" id="higherThan25" />
    Wood = <span id="wood">0</span>
  </div>

</body>

</html>


推荐阅读