日期:2014-05-16  浏览次数:20424 次

JS实现相加
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>test</title>
  <script type="text/javascript">
function add(){
    var var1 = parseFloat(document.getElementById('id1').value);
    var var2 = parseFloat(document.getElementById('id2').value);
    
    if (var1 == 'NaN' && var2 != 'NaN') { 
       document.getElementById('id3').value = parseFloat(var2);
    } else if (var1 != 'NaN' && var2 == 'NaN') {
      document.getElementById('id3').value = parseFloat(var1);
    } else if (var1 == 'NaN' && var2 == 'NaN') {
      document.getElementById('id3').value = 0;       
    }

    document.getElementById('id3').value = parseFloat(var1) + parseFloat(var2);
   }
  </script>
</head>
<body>
<input type="text" id="id1" onkeyup="add()">
<input type="text" id="id2" onkeyup="add()">
<input type="text" id="id3">
</body>
</html>

这是哪里错了 

小弟新人 求解 谢谢

------解决方案--------------------

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[type='text']:not(:eq(2))").blur(function(){
var a=$("#id1").val();
var b=$("#id2").val();
if(a!=''&& b==''){
$("#id3").val(parseInt(a));
}
if(b!=''&& a==''){
$("#id3").val(parseInt(b));
}
if(b!=''&& a!=''){
$("#id3").val(parseInt(b)+parseInt(a));
}
if(b==''&& a==''){
$("#id3").val("请填写1,2两个文本框的值");
}
});
})
</script>
</head>
<body>
<input type="text" id="id1" />
<input type="text" id="id2" />
<input type="text" id="id3"/>

------解决方案--------------------
没有那么复杂吧:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>test</title>
  <script type="text/javascript">
function add(){
    // 如果不是数字,或者没有填写就默认为0
    var var1 = parseFloat(document.getElementById('id1').value) 
------解决方案--------------------
 0;
    var var2 = parseFloat(document.getElementById('id2').value) 
------解决方案---