我收到“无法从 getElementById 设置属性‘innerHTML’为 null,但我的 HTML 元素具有正确的 ID,我的脚本也是如此。
我是 JavaScript 新手,所以如果我遗漏了一些明显的内容,请告诉我!谢谢!
这是完整的 fiddle : fiddle :http://jsfiddle.net/xPLD4/1/
这是我遇到问题的部分。 脚本:
function prices() {
document.getElementById("regular").innerHTML = '$' + setPrices.regular + ' /gallon';
document.getElementById("regPlus").innerHTML = '$' + setPrices.regularPlus + ' /gallon';
document.getElementById("premium").innerHTML = '$' + setPrices.premium + ' /gallon';
document.getElementById("status").innerHTML = "Status: No Automobile Present";
var carPresent = false;
}
//generates prices on pump display
window.onload = prices;
var pumpDisplayOne = 1000;
document.getElementById("pumpDisplayOne").innerHTML = "Total gallons pumped on this pump: " + pumpDisplayOne;
HTML:
<h3>Pump 1</h3>
<h4 id="pumpDisplayOne">Gallons</h4>
<button type="button" class="paybutton" onclick="pay()">Pay!</button>
最佳答案
您必须在 DOMReady 之后运行您的 javascript 代码,如果您的 script
标签位于 head
,先下移</body>
,或者将所有代码放入onload
事件。
这是我的jsFiddle update , 这样可行。
关于javascript - 无法设置 null 错误的innerHTML。虽然 html ID 存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17691247/