Javascript:UncaughtTypeError:无法设置属性';innerHTML';空的
我浏览了几个问题,但找不到任何帮助。 顺便说一句,这是我第一次在这里问问题,所以我可能做得不对。不管怎么说,下面这句话给我带来了问题Javascript:UncaughtTypeError:无法设置属性';innerHTML';空的,javascript,html,Javascript,Html,我浏览了几个问题,但找不到任何帮助。 顺便说一句,这是我第一次在这里问问题,所以我可能做得不对。不管怎么说,下面这句话给我带来了问题 /* cursorPps defined above */ document.getElementById("cursorPps").innerHTML = cursorPps; cursorPps变量已定义。有人能指出是什么其他可能的因素导致了这个错误吗 编辑:顺便说一下,问题是它没有更新HTML上的值,尽管变量的值发生了变化 HTML: 确保 您有一个元素
/* cursorPps defined above */
document.getElementById("cursorPps").innerHTML = cursorPps;
cursorPps
变量已定义。有人能指出是什么其他可能的因素导致了这个错误吗
编辑:顺便说一下,问题是它没有更新HTML上的值,尽管变量的值发生了变化
HTML:
确保
- 您有一个元素具有该ID
- 该元素位于运行Javascript之前的页面上
- 将JS的执行绑定到元素出现在页面上后发生的事件(上一个事件的后续)
- 已填充cursorPps变量
您的DOM中是否有id为
cursorPps
的元素?它将区分大小写。请与我们共享HTML代码。@epascarello我把它放在底部,就在结束tagOh ok I see.之前。。我想我已经知道如何修复它了。谢谢@Cookie Monster我解决了它。那么我该如何结束这个问题呢对不起,我是个傻瓜,嗯,你说的第三点和第四点是什么意思?你的第三点不是问题所在,因为代码是响应点击事件运行的。到第四点我不知道你在说什么。
<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>
//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);
<div id="myDiv"></div>
var length = document.querySelectorAll('#myDiv').length;
if(length > 0) {
// This element exists in the DOM tree
}
<body>
<div id="myDiv"></div>
<script>
var length = document.querySelectorAll('#myDiv').length;
console.log(length);
</script>
</body>
if(cursorPps != undefined)