gpt4 book ai didi

javascript - 我正在尝试让 Javascript 中的innerHTML 函数正常工作

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

我希望加热答案出现在加热表面 (mm) 旁边,但我无法使其工作。我只从 chrome 控制台收到以下错误消息

Uncaught TypeError: Cannot read property 'value' of null 

我知道其他一切都有效,因为我添加了一个警报框,但我需要innerHTML才能工作。

这是 html:

 <html>

<head>
<script type="text/javascript" src="pipeheaterfunction.js">
</script>
</head>

<body>

<table>
<tr><td>Inner Diameter (mm):</td>
<td><input id="dia" onkeypress="pipeheater();"></td>

<tr><td>Pipe Thickness (mm):</td>
<td><input id="thi" onkeypress="pipeheater();"></td>

<tr><th>Calculate heater:</th>
<td><button onclick="pipeheater();">Calculate</button></td></tr>

<tr><td>Heating Surface(mm):</td>
<td><span class="output" id="surface"></span></td></tr>
</table>

</body>


</html>

这是 JavaScript 代码:

function pipeheater(){ //dia is the inner diameter of a pipe, thi is the pipe thickness

var dia = document.getElementById("dia").value;
var thi = document.getElementById("thi").value;
var hsur; //hsur is the heating surface required for a certain pipe in mm

hsur = 5*Math.sqrt(((dia-thi)*thi)/2);

var surface = hsur;


if(surface>0){
surface.innerHTML=surface.toFixed(1);
alert(surface.toFixed(1));
}


}

window.onload=pipeheater();

最佳答案

您的脚本中有两个错误。首先,设置时

window.onload = pipeheater();

pipeheater 会立即调用,它不会等待 window.onload 被触发,并且在尝试读取尚不存在的元素的值时会出现错误。您可以像这样修复此问题:

window.onload = pipeheater;

其次,您尝试使用 hsurinnerHTML,它是一个数字。您需要为实际的 HTML 元素定义一个变量。以下是您的固定代码。

function pipeheater() {
var dia = document.getElementById("dia").value,
thi = document.getElementById("thi").value,
hsur = 5 * Math.sqrt(((dia - thi) * thi) / 2),
surface = document.getElementById("surface");

if (hsur > 0) {
surface.innerHTML = hsur.toFixed(1);
alert(hsur.toFixed(1));
}
}

window.onload = pipeheater;

您可以在jsFiddle查看其工作原理。 。我建议您在使用 diathi 进行任何计算之前验证它们的值。另外,使用 onchange 而不是 onkeypress 可能会让用户更舒服,并且会为您提供更可靠的结果。

关于javascript - 我正在尝试让 Javascript 中的innerHTML 函数正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17785744/

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