2010-07-29 53 views
0
<html> 
<head> 
<script language="javascript"> 
function fadd() 
{ 
var first,sec,res; 
first=parsefloat(document.forms[0].txt1st.value); 
sec=parsefloat(document.forms[0].txt2nd.value); 
res=first+sec; 
document.forms[0].txtres.value=res; 
} 
</script> 
</head> 


<body> 
<form> 
Enter 1st number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="txt1st" id="txt1st" type="text"> 
</br> 
Enter 2nd number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="txt2nd" id="txt2nd" type="text"> 
</br> 
Result &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp; 
<input name="txtres" id="txtres" type="text"> 
</br> 
<input name="btnadd" id="btnadd" type="button" value="+" onclick="fadd()"> 
<input name="btnsub" id="btnsub" type="button" value="-" onclick="fminus()"> 
<input name="btndiv" id="btndiv" type="button" value="%" onclick="fdiv()"> 
<input name="btnmul" id="btnmul" type="button" value="*" onclick="fmult()"> 
</form> 
</body> 
</html> 

回答

3

编辑:此问题已发布在问题更新之前。

对于以数字开头的属性名称,您不能使用点表示法。

请勿使用document.forms[0].1st。使用document.getElementById('1st')。这同样适用于2nd

var x = {}; 

x['1st'] = 10; 

console.log(x['1st']); // This works 
console.log(x.1st); // This doesn't - Syntax error 
+0

+1,另外数字作为ID中的第一个字符是无效的html .. – 2010-07-29 10:59:31

+1

@Gaby:是的,好点...另外,还有'parseFloat'问题,因为[@strager identified](http:// stackoverflow.com/questions/3361694/need-help-on-simple-calculator/3361717#3361717) – 2010-07-29 11:00:44

3

两件事情:

parsefloat应该parseFloat。函数名称区分大小写。

1st不是合法的ID(我认为它也不是合法的名称)。此外,您不能用点符号(x.y.z)引用非标识符(1st不是标识符,因为它以数字开头)。您可以尝试document.forms[0]['1st'].value,或者您可以尝试将1st重命名为first(和2ndsecond)。

+0

谢谢我将parsefloat改为parseFloat,它工作:) – sayuki288 2010-07-29 11:22:22

0

此外,你应该改变这一行:

document.forms[0].textres.value=res; 

要这样:

document.forms[0].txtres.value=res; 

听其他职位的建议在这里和这样做了以后,你的代码应该工作正常。