我浏览了几个问题但我找不到任何帮助。 顺便说一下,这是我第一次在这里提问,所以我可能不会采用正确的方式。无论如何,以下行引起了我的问题
/* cursorPps defined above */
document.getElementById("cursorPps").innerHTML = cursorPps;
cursorPps
变量已经定义。有人可以指出其他可能的东西可能导致这个错误吗?
编辑:顺便说一下,问题在于它没有更新HTML上的值,尽管变量的值会发生变化。
HTML:
<html>
<head>
<title>Potato Clicker</title>
<link rel="stylesheet" type="text/css" href="interface.css">
</head>
<body>
<div id="left">
<img id="potato-img" onClick="potatoClick(clickPower)" src="stockvault-potatoes107220.jpg" width="300" height="300">
<br>
<div id="mainDisplay">
<span id="potatoes">0</span> <br> potatoes
<br>
<br>
Producing <span id="pps">0</span> potatoes per second
<br>
</div>
Cursors: <span id="cursors">0</span>
</div>
<div id="middle">
<div id="buildings" onClick="buyCursor()"> Buy Cursor </div>
</div>
<script src="main.js"></script>
</body>
</html>
使用Javascript:
//variables
var potatoes = 0; //potatoes
var clickPower = 1; //potatoes gained per click
var pps = 0; //potatoes per second
var cursors = 0; //cursors
var cursorCost; //cost of cursor
var cursorPps = 0; //total cursor potatoes per second
var cursorBuy; //cursor buy button
//functions
function potatoClick(number) {
potatoes = potatoes + number;
document.getElementById("potatoes").innerHTML = potatoes;
}
function buyCursor() {
var cursorCost = Math.floor(10 * Math.pow(1.2,cursors));
if (potatoes >= cursorCost) {
pps = pps - cursorPps;
cursors = cursors + 1;
potatoes = potatoes - cursorCost;
cursorPps = cursorPps + 1;
pps = pps + cursorPps;
document.getElementById("potatoes").innerHTML = potatoes;
document.getElementById("cursors").innerHTML = cursors;
document.getElementById("cursorPps").innerHTML = cursorPps;
document.getElementById("pps").innerHTML = pps;
}
else {
alert("Not enough potatoes!")
}
var nextCost = Math.floor(100 * Math.pow(1.2,cursors));
document.getElementById('cursorCost').innerHTML = nextCost;
}
window.setInterval(function () {
if (pps > 0) {
potatoClick(pps);
}
}, 1000);
答案 0 :(得分:3)
确保
这是一个简单的codepen,演示了一种方法http://codepen.io/leopic/pen/wDtIB
答案 1 :(得分:2)
<div id="myDiv"></div>
您有一个具有该ID的元素
var length = document.querySelectorAll('#myDiv').length;
if(length > 0) {
// This element exists in the DOM tree
}
您将JS的执行绑定到元素在页面上发生的事件(之前的后续跟踪)
<body>
<div id="myDiv"></div>
<script>
var length = document.querySelectorAll('#myDiv').length;
console.log(length);
</script>
</body>
已填充cursorPps变量
if(cursorPps != undefined)