為什么會這樣
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title>?
? <script type="text/javascript">
?? function count(txt1,txt2,select){
??? switch(select) {
??????? case "+":
?????????? result = parseFloat(txt1) + parseFloat(txt2);
??????????? break;
??????? case "-":
??????????? result = parseFloat(txt1) - parseFloat(txt2);
??????????? break;
??????? case "*":
??????????? result = parseFloat(txt1) * parseFloat(txt2);
??????????? break;
??????? default:
??????????? result = parseFloat(txt1) / parseFloat(txt2);
??? }
??? document.getElementById("fruit").value = parseFloat(result);
???
?? }
? </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>
2019-08-30
按照你寫的代碼,你獲取到的值為undefined所以你不管怎么點=號,都只會得出NaN。
用代碼表示你的情況:
正確的代碼應為
2019-08-25
result? ?沒有定義,他不是一個數字所以會報這樣的問題,你可以在switch上面定義一下,
方法一:var sum = Number("");或者方法二:var sum = 0;
function count() {
//獲取第一個輸入框的值
var first = document.getElementById("txt1").value;
//獲取第二個輸入框的值
var second = document.getElementById("txt2").value;
//獲取選擇框的值
var sel = document.getElementById("select").value;
if (!isNaN(first) && !isNaN(second)) {
//方法一:
//var sum = Number("");
//方法二:
var sum = 0;
switch (sel) {
case "+":
sum += parseFloat(first) + parseFloat(second);
break;
case "-":
sum += parseFloat(first) - parseFloat(second);
break;
case "*":
sum += parseFloat(first) * parseFloat(second);
break;
case "/":
sum += parseFloat(first) / parseFloat(second);
break;
default:
}
document.getElementById("fruit").value = sum;
} else {
console.log("輸入的不是數字");
}
}
2019-08-19
輸入框的兩個值你沒有獲取,以及符號的那個選擇框的值你也沒獲取
?function count(){
? ? ? ?
? ? //獲取第一個輸入框的值
? ? var num1=document.getElementById("txt1").value;
//獲取第二個輸入框的值
var num2=document.getElementById("txt2").value;
//獲取選擇框的值
var fuhao=document.getElementById("select").value;
var sum
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
switch(fuhao){
? ? case "+":sum=parseInt(num1)+parseInt(num2);
? ? break;
? ? case "-":sum=num1-num2;
? ? break;
? ? case "*":sum=num1*num2;
? ? break;
? ? case "/":sum=num1/num2;
? ? break;
? ? default:
? ??
}
? ? //設置結果輸入框的值?
? ? document.getElementById("fruit").value=sum;
? ?}