javascript - 如何在变量为假时连续添加点并显示它(js)
问题描述
我正在使用 HTML 和 JS 制作游戏,需要在游戏未结束时不断添加点并通过 document.getElementById() 显示它。我的预期是每秒钟 5 美元将被添加到积分中,并以这种格式显示:“金钱:5”。我所拥有的只是“钱:”,所以我认为 JavaScript 代码会有一些不正确的地方,会不断增加 5 美元。我确实收到了一条错误消息:“未捕获的类型错误:无法将 innerHTML 的属性发送到 null”我最初开始使用“window.onload = function()”修复该问题,但随后页面的 CSS 已损坏并完全关闭我设计的。这是代码:
HTML:
<h3> <b> Game Statistics </b> </h3>
<span> Dollars Earned Per Second: <b> </b></span>
<br>
<br>
<span id = "money"> Money: <b> </b> </span>
<br>
<br>
<span> Carbon Footprint Decrease Rate: <b> </b></span>
</div>
<div id = "garbagecan">
<img src = "gbg.png" id = "gbg">
<p> Garbage Can </p>
<p> Status: Unlocked </p>
<p id = "description"> 0.1% decrease rate: $5 per second </p>
<button> Increase to 0.5% decrease rate for $20 </button>
</div>
JS:
const decrease_rate_required = 0;
var user_decrease_rate = 0.1;
var user_money = 0;
var tools_bought = 1;
var hasWon = false;
const garbage_box = {
status: "unlocked",
numOfUpgrades: 9,
index: 0,
currentDecreaseRate = 0.1,
rateOfMoney: 5,
maxedOut: false,
decreaseRateUpgrades: [0.5, 0.6, 0.75, 0.9, 1, 1.25, 1.5, 1.75, 1.85, 2],
upgradeCosts: [ 20, 25, 30, 40, 50, 75, 100, 125, 150, 200]
}
while(hasWon === false) {
user_money = user_money + garbage_box.rateOfMoney
document.getElementById("money").innerHTML = "Money: " + user_money
}
解决方案
我把它改成
currentDecreaseRate = 0.1,
了这个 -currentDecreaseRate:0.1,
。while 循环不是您在这里需要的。您必须在此处使用间隔来更新值。
const decrease_rate_required = 0;
var user_decrease_rate = 0.1;
var user_money = 0;
var tools_bought = 1;
var hasWon = false;
const garbage_box = {
status: "unlocked",
numOfUpgrades: 9,
index: 0,
currentDecreaseRate:0.1,
rateOfMoney: 5,
maxedOut: false,
decreaseRateUpgrades: [0.5, 0.6, 0.75, 0.9, 1, 1.25, 1.5, 1.75, 1.85, 2],
upgradeCosts: [ 20, 25, 30, 40, 50, 75, 100, 125, 150, 200]
}
setInterval(()=>{
// Check if hasWon is false
if(hasWon == false) {
// Update money
user_money = user_money + garbage_box.rateOfMoney
document.getElementById("money").innerHTML = "Money: " + user_money
}
// Run the function every 1000 milliseconds that is 1s.
},1000)
<span id="money"> Money: <b> </b> </span>
推荐阅读
- sitecore - Sitecore Experience Accelerator (SXA) 安装错误
- java - 发送 Multipart MimeMessage 会发送一封空电子邮件
- javascript - 我如何创建一个带有 2 个键的 JS 对象
- laravel - Laravel:尺寸验证不起作用
- android - 返回动画/新动画
- javascript - 在事件单击时按顺序一一显示数组的元素
- ios - 如何填充 SCNBox 的内部
- sip - 可以听到音频但无法确认状态并在 20->30 秒后结束通话 pjsip
- sql - sql 根据具有现有值的其他列创建列
- javascript - 语义 UI 未按预期工作