JavaScript加減乘數運算

螞蟻小編發表於2018-05-31

分享一段程式碼例項,它實現了簡單的加減乘數運算功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
function count() {
  var txt1 = parseInt(document.getElementById('txt1').value);
  var txt2 = parseInt(document.getElementById('txt2').value);
  var sym = document.getElementById('select').value;
  var res = document.getElementById('result');
  switch (sym) {
    case '+':
      res.value = txt1 + txt2;
      break;
    case '-':
      res.value = txt1 - txt2;
      break;
    case '*':
      res.value = txt1 * txt2;
      break;
    case '/':
      if (txt2 == 0) {
        res.value = undefined;
        alert("分母不能為0!!");
        break;
      } else {
        res.value = txt1 / txt2;
    }
  }
}
window.onload = function () {
  var done = document.getElementById("done");
  done.onclick = function () { count() }
}
</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=' = ' id="done"/>
  <input type='text' id='result' />
</body>
</html>

相關文章