[問題] 請問我想用javsscript做加法運算

看板Ajax作者 (Ying=))時間11年前 (2013/03/14 18:32), 編輯推噓2(205)
留言7則, 3人參與, 最新討論串1/1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "" rel="nofollow">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="" rel="nofollow">http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>123</title> <script language="javascript"> function myfunc(){ var s1=document.form1.t1.value; var s2=document.form1.t2.value; s3=s1+s2 s4=s1%s2 alert("數字1+數字2="+s3+","+"餘數="+s4); } </script> </head> <body> <form id="form1" name="form1" method="post" action=""> <p>&nbsp;</p> <table border="1"> <tr> <td>數字1:</td> <td><input name="t1" type="text" id="t1" /></td> </tr> <tr> <td>數字2:</td> <td><input name="t2" type="text" id="t2" /></td> </tr> </table> <p> <input type="button" name="b1" id="b1" value="ok" onClick="myfunc()"/> </p> <p>&nbsp;</p> </form> <p>&nbsp;</p> </body> </html> 以上是我的程式碼~ 可是當網頁出來後,自行設兩個數但都不會等於加法 例如:我第一個數字輸入9第二個數字輸入4他不會等於13 它會顯示成94..... 有人知道該如何解決嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.165.234.118 ※ 編輯: ying0902 來自: 118.165.234.118 (03/14 18:36)

03/14 18:52, , 1F
s3-(-s4)
03/14 18:52, 1F

03/14 18:53, , 2F
喔不對 是s1-(-s2) 因為從input取得的value是字串
03/14 18:53, 2F

03/14 18:53, , 3F
所以s1+s2會被當成字串相加 可改用減法強迫兩者轉換為數值
03/14 18:53, 3F

03/14 19:08, , 4F
謝謝~~太感謝了Q~Q
03/14 19:08, 4F

03/14 19:53, , 5F
vparseInt("9") 也可以轉字串變數字
03/14 19:53, 5F

03/14 20:38, , 6F
建議加上第二個參數parseInt('9',10)
03/14 20:38, 6F

03/14 20:39, , 7F
或是'9'*1也可
03/14 20:39, 7F
文章代碼(AID): #1HGQSlnE (Ajax)