我正在尝试制作一个三角形的斜边计算器。首先你放一条腿,然后另一条腿,然后你会得到斜边。但是,如果你先填写第二个框,它会说NaN。我知道它并不重要,但有没有办法摆脱它,所以它说“0”,直到两个盒子都填满?这是代码:
<html>
<head>
<script type="text/javascript">
function hypotenuse(a,b){
return Math.sqrt(a*a + b*b);
}
</script>
</head>
<body>
<input type="button" value="Hypoteneuse";" />
A:<input type="text" id="leg1" size="2";" />
B:<input type="text" id="leg2" size="2" onChange="document.getElementById('result').value=hypotenuse(parseInt(document.getElementById('leg1').value),parseInt(document.getElementById('leg2').value));" />
Hypotenuse:<input type="text" placeholder="0" id="result" size="2" />
</body>
</html>
答案 0 :(得分:1)
您可以在第一个输入上设置默认值:
<input type="text" id="leg1" size="2" value="0" />
或者您可以将函数绑定到单击按钮并在尝试计算之前进行一些验证(fiddle):
var leg1 = document.getElementById('leg1');
var leg2 = document.getElementById('leg2');
function hypotenuse(a,b){
return Math.sqrt(a*a + b*b);
}
document.getElementById('submit').addEventListener('click', function() {
// Check both fields are populated. This validation could
// be more sophisticated if you needed it to be.
if (leg1.value !== '' && leg2.value !== '') {
document.getElementById('result').value = hypotenuse(parseInt(leg1.value),parseInt(leg2.value));
} else {
// You could display an error message here
console.log('Please fill out both fields');
}
});
答案 1 :(得分:0)
您可以使用isNaN()
检查您的值是否存在:
<script type="text/javascript">
function hypotenuse(a,b){
if (isNaN(a) || isNaN(b)) {
return 0;
}
return Math.sqrt(a*a + b*b);
}
</script>
答案 2 :(得分:0)
你可以这样做:
使用Javascript:
function hypotenuse(){
var angleA = document.getElementById['leg1'].val;
var angleB = document.getElementById['leg2'].val;
if(angleA != '' && angleB != ''){
var angleC = Math.sqrt(a*a + b*b);
document.getElementById['result'].val = angleC;
}
}
您的HTML看起来像
A:<input type="text" id="leg1" size="2" onblur="hypotenuse()" />
B:<input type="text" id="leg2" size="2" onblur="hypotenuse()" />
Hypotenuse:<input type="text" placeholder="0" id="result" size="2" />