我正在开发一款名为Factory Tycoon的游戏,并发现了一个我无法自行解决的错误。你得到的每一秒加上你的物品每秒的物品数量,但它没有这样做。随意测试代码。代码:
<!DOCTYPE html>
<html>
<head>
<title>Factory Tycoon</title>
<script type="text/javascript">
var money = 1000;
var items = 0;
var itemsps = 1;
var dropper1Cost = 100;
var dropper1Audio = new Audio('Audio/dropper1Sound.mp3');
function addDropper() {
if (money <= dropper1Cost - 1) {
alert('Not Enough Money.')
}
if (money >= dropper1Cost) {
dropper1Audio.play()
itemsps += 1;
money -= dropper1Cost;
dropper1Cost += 100;
}
}
setInterval(function renderMoney() {
document.getElementById('money').innerHTML = "Money:" + money;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('items').innerHTML = "Items Processed:" + items;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('itemsps').innerHTML = "Items Processed Per Second:" + itemsps;
}, 1000)
</script>
</head>
<h4 id="money"></h4>
<h4 id="items"></h4>
<h4 id="itemsps"></h4>
<body>
<img src="Images/dropper1IMG.png" onclick="addDropper()">
</html>
没有太多代码,因为我今晚才开始开发它。)。
答案 0 :(得分:0)
代码中存在一些问题:
<h4>
元素必须位于<body>
元素</body>
结束标记setInterval
,这会导致错误,所以我将它们包装在init
函数中并在体载上调用 旁注,此代码可以使用addEventListener
针对加载事件等进行优化,但是这里有一个开始
<!DOCTYPE html>
<html>
<head>
<title>Factory Tycoon</title>
<style>
span { display: inline-block; padding: 5px; background: #ddd; }
</style>
<script type="text/javascript">
var money = 1000;
var items = 0;
var itemsps = 1;
var dropper1Cost = 100;
var dropper1Audio = new Audio('Audio/dropper1Sound.mp3');
function addDropper() {
if (money <= dropper1Cost - 1) {
alert('Not Enough Money.')
}
if (money >= dropper1Cost) {
dropper1Audio.play()
itemsps += 1;
money -= dropper1Cost;
dropper1Cost += 100;
}
}
function init() {
setInterval(function renderMoney() {
document.getElementById('money').innerHTML = "Money:" + money;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('items').innerHTML = "Items Processed:" + items;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('itemsps').innerHTML = "Items Processed Per Second:" + itemsps;
}, 1000)
}
</script>
</head>
<body onload="init();">
<h4 id="money"></h4>
<h4 id="items"></h4>
<h4 id="itemsps"></h4>
<span onclick="addDropper()">Click Me</span>
</body>
</html>