javascript - 在 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>
解决方案
- 向 DOM 添加一个按钮并将其隐藏。当它超过阈值时,将显示属性从隐藏切换到阻止。
- 确保我们在发生增量的 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>
推荐阅读
- flutter - 在 Flutter 2.0.4 版本上删除了 Listview 计数和构建器属性
- asp.net - 如何在 ASP.NET Core 3.1 API 中显示指定的列数据
- html - Bootstrap 不会将我的两张表放在相邻的两列中
- firefox - 我可以在浏览器中延迟或禁用鼠标悬停弹出窗口吗?
- google-admin-sdk - 在 Google 工作区和管理控制台中删除组后再次创建同一组时,API 中出现 409 冲突问题的警告
- python - Matplotlib 实时更新
- c++ - 获取数组输入并打印数组(C++)
- node.js - 快速会话在页面重新加载后过期
- amazon-web-services - 如何保持容器在 ECS 中运行
- vba - VBA - 比较两个文件的布局