減乘除都沒問題,為什么加法有問題?1+1=11????對了還有亂碼
<!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;
? ? if(c=="+"){
? ? d=a+b;
? ? }else if(c=="-"){
? ? d=a-b;
? ? }else if(c=="*"){
? ? d=a*b;
? ? }else{
? ? d=a/b;
? ? }
? ? document.getElementById("fruit").value = d;
? ? //獲取第一個輸入框的值
//獲取第二個輸入框的值
//獲取選擇框的值
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? //設置結果輸入框的值?
? ?}
? </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()" /> <!--通過 = 按鈕來調(diào)用創(chuàng)建的函數(shù),得到結果-->?
? ?<input type='text' id='fruit' /> ??
?</body>
</html>
2018-06-05
取得的值是字符串,所以按照字符串的運算是字符串相連??梢允褂胮arseInt()將字符串轉換成數(shù)值。
? ? var a =parseInt(document.getElementById("txt1").value);
? ? var b =parseInt(document.getElementById("txt2").value);
2018-06-13
你在input中輸入的內(nèi)容屬于字符串類型。你可以這樣來測試,在你原來的JS代碼中加入console.log(typeof a)就能得到你寫入的內(nèi)容屬性是string。既然是string, 那么+號就把它們連接起來,而不是相加取和。
2018-06-09
不行啊