请帮助我理解为什么我的单击调用没有调用脚本中的函数。
我尝试在其他地方调用onclick,但似乎仍然无法正常工作。
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body {margin: 30px;}
</style>
</head>
<body>
<form>
Energy Spent in Hours:
<input type="number" id="spent"/>
<br>
<input type="button" value="Calculate" id="calculate" onClick="start();"/>
</form>
<p id="final"></p>
<script>
document.getElementById("calculate").onClick="start()";
function start(){
x=document.getElementById("spent").value;
if(x<50)
document.getElementById("final").innerHTML="The hours are "+x+" multiplied with 3.5 is "calc(x,3.5);
else
if(x>50 && x<=150)
document.getElementById("final").innerHTML="The hours are "+x+" multiplied with 4 is "calc(x,4);
else
if(x>150 && x<=250)
document.getElementById("final").innerHTML="The hours are "+x+" multiplied with 5.2 is "calc(x,5.2);
else
if(x>250 && x<=500)
document.getElementById("final").innerHTML="The hours are "+x+" multiplied with 6 is "calc(x,6);
else
document.getElementById("final").innerHTML=1000;
}
function calc(z,y)
{
return z*y;
}
</script>
</body>
</html>
我需要在按下“计算”时获取计算结果。
答案 0 :(得分:2)
您遇到了很多语法错误,并且错误地绑定了事件,并且错误号为50。
function start() {
x = document.getElementById("spent").value;
if (x <= 50)
document.getElementById("final").innerHTML = "The hours are " + x + " multiplied with 3.5 is " + calc(x, 3.5);
else if (x > 50 && x <= 150)
document.getElementById("final").innerHTML = "The hours are " + x + " multiplied with 4 is " + calc(x, 4);
else if (x > 150 && x <= 250)
document.getElementById("final").innerHTML = "The hours are " + x + " multiplied with 5.2 is " + calc(x, 5.2);
else if (x > 250 && x <= 500)
document.getElementById("final").innerHTML = "The hours are " + x + " multiplied with 6 is " + calc(x, 6);
else
document.getElementById("final").innerHTML = 1000;
}
function calc(z, y) {
return z * y;
}
document.getElementById("calculate").addEventListener("click", start);
body {
margin: 30px;
}
<form>
Energy Spent in Hours:
<input type="number" id="spent" />
<br>
<input type="button" value="Calculate" id="calculate" />
</form>
<p id="final"></p>