我一直在尝试制作一个可以从 switch 调用 JavaScript 案例的按钮。我尝试创建的脚本应该计算正方形的周长和面积,但它似乎不起作用。
<html>
<body>
<form>
<input type=text id="num"><br>
<input type="button" value="area" id="abut" onclick=" return calc(this.value)">
<input type="button" value="per" id="pbut" onclick=" return calc(this.value)">
</form>
<script>
function calc(count) {
var a =parseInt(document.getElementById("num").value);
var w;
if isNaN(a) {
alert("Input a number");
}
else {
switch(count) {
case 'area' :
w=a*a;
break;
case 'per' :
w=a*4;
break;
}
document.getElementById("res").innerHTML = w;
}
}
</script>
<p id="res"></p>
</body>
</html>
最佳答案
拼写错误:if isNaN(a)
必须位于括号之间。应该是 if (isNaN(a))
function calc(count)
{
var a = parseInt(document.getElementById("num").value);
var w;
if (isNaN(a))
{
alert("Input a number");
}
else
{
switch (count)
{
case 'area':
w = a * a;
break;
case 'per':
w = a * 4;
break;
}
document.getElementById("res").innerHTML = w;
}
}
<html>
<body>
<form>
<input type=text id="num">
<br>
<input type="button" value="area" id="abut" onclick=" return calc(this.value)">
<input type="button" value="per" id="pbut" onclick=" return calc(this.value)">
</form>
<p id="res"></p>
</body>
</html>
关于Javascript 将 switch 的大小写绑定(bind)到 html 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41431166/