gpt4 book ai didi

Javascript:未捕获类型错误:无法设置 null 的属性 'innerHTML'

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:13 24 4
gpt4 key购买 nike

我浏览了几个问题,但找不到任何帮助。顺便说一下,这是我第一次在这里提问,所以我可能不会以正确的方式提问。不管怎样,下面一行是我的问题

/* 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()"> &nbsp; Buy Cursor &nbsp; </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);

最佳答案

确保

  • 您有一个元素具有该 ID
  • 元素在运行 Javascript 之前就在页面上
  • 将 JS 的执行绑定(bind)到元素位于页面上之后发生的事件(之前的后续事件)
  • 已填充 cursorPps 变量

这是一个简单的代码笔,演示了一种方法 http://codepen.io/leopic/pen/wDtIB

关于Javascript:未捕获类型错误:无法设置 null 的属性 'innerHTML',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20659932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com