請問這是為什么?謝謝!
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title> ?
? <script type="text/javascript">
? ?function count(){?
? ? //獲取第一個輸入框的值
? ? //獲取第二個輸入框的值
//獲取選擇框的值
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? //設置結果輸入框的值?
? ? var one=document.getElementById("txt1").value;
var two=document.getElementById("txt2").value;
var objselect=document.getElementById("select").value;
switch(objselect){
case "+" : return document.getElementById("fruit").value=one+two;
case "-" : return document.getElementById("fruit").value=one-two;
case "*" : return document.getElementById("fruit").value=one*two;
case "/" : return document.getElementById("fruit").value=one/two;
}
? ?}
? </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>
?
請問各位大神,為什么我這樣用加法那里出來的是兩個字符串連起來?而用parseInt()就可以正常?
2015-06-04
因為你獲取的是字符串,不轉化相加當然是字符串拼接...
parseInt的作用就是把字符串轉化為整數(適用于數字字符串),parseFloat轉為浮點數
2015-06-04
你獲得的值的數據類型如果其中一個為字符串,那么計算結果會轉化為字符串。
parseInt是全局的函數,用來將字符串類型轉化為int類型。所以遇到這種情況應該考慮你的值類型是否是你所希望的。