gpt4 book ai didi

javascript - document.getElementById ('id' ) is null javascript 错误

转载 作者:行者123 更新时间:2023-12-04 02:23:43 25 4
gpt4 key购买 nike

出于某种原因,我在第 7 行收到一个 document.getElementById('id') is null JS 错误,其中包含以下标记和脚本:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
document.getElementById('calculate').onclick = function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;

root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa

document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
};
document.getElementById('erase').onlick = this.form.reset();
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button">
<input id="erase" value="Clear" type="button">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

这里真正的问题是什么?

最佳答案

确实是null .您的元素在页面上尚不存在。

或者:

  • 移动您的 <script>在您的代码下方屏蔽
  • 添加 window.onload事件。

关于javascript - document.getElementById ('id' ) is null javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3911350/

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