字符连接符加号

来源:互联网 发布:ipad打击垫软件 编辑:程序博客网 时间:2024/04/28 22:16

因为javascript中的+号,有的时候会默认是连接符,所以会出现以下的这种情况

<!DOCTYPE html><html> <head>  <title> 事件</title>    <script type="text/javascript">   function count(){   var a=document.getElementById('txt1').value;   var b=document.getElementById('txt2').value;   var c=document.getElementById('select').value;   var t;   switch(c)    {     case "+":     t=a+b;     break;       case "-":     t=a-b;     break;     case "*":     t=a*b;     break;     default:     t=a/b;     break;    } document.getElementById("fruit").value=t;   }  </script>  </head>  <body>   <input type='text' id='txt1' />    <select id='select'><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option>   </select>   <input type='text' id='txt2' />    <input type='button' value=' = ' onclick="count()"/>   <input type='text' id='fruit'/>    </body></html>


 

 

这样得出来的结果,运行测试会出现1+1=11的结果,因为默认为字符,然后加号将其连接起来了

如果想要得到正确的结果,在给a,b复制的时候,进行格式强转,比如parseInt()强制转为整数,进行运算(注意,parseInt的大小写格式)

<!DOCTYPE html><html> <head>  <title> 事件</title>    <script type="text/javascript">   function count(){   var a=parseInt(document.getElementById('txt1').value);   var b=parseInt(document.getElementById('txt2').value);   var c=document.getElementById('select').value;   var t;   switch(c)    {     case "+":     t=a+b;     break;       case "-":     t=a-b;     break;     case "*":     t=a*b;     break;     default:     t=a/b;     break;    } document.getElementById("fruit").value=t;   }  </script>  </head>  <body>   <input type='text' id='txt1' />    <select id='select'><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option>   </select>   <input type='text' id='txt2' />    <input type='button' value=' = ' onclick="count()"/>   <input type='text' id='fruit'/>    </body></html>


 

0 0