作者ying0902 (Ying=))
看板Ajax
標題[問題] 請問我想用javsscript做加法運算
時間Thu Mar 14 18:32:11 2013
<!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>
<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> </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> </p>
</form>
<p> </p>
</body>
</html>
以上是我的程式碼~
可是當網頁出來後,自行設兩個數但都不會等於加法
例如:我第一個數字輸入9第二個數字輸入4他不會等於13
它會顯示成94.....
有人知道該如何解決嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.165.234.118
※ 編輯: ying0902 來自: 118.165.234.118 (03/14 18:36)
1F:推 s25g5d4:s3-(-s4) 03/14 18:52
2F:→ s25g5d4:喔不對 是s1-(-s2) 因為從input取得的value是字串 03/14 18:53
3F:→ s25g5d4:所以s1+s2會被當成字串相加 可改用減法強迫兩者轉換為數值 03/14 18:53
4F:→ ying0902:謝謝~~太感謝了Q~Q 03/14 19:08
5F:→ waneblade:vparseInt("9") 也可以轉字串變數字 03/14 19:53
6F:推 s25g5d4:建議加上第二個參數parseInt('9',10) 03/14 20:38
7F:→ s25g5d4:或是'9'*1也可 03/14 20:39