JavaScript加减乘数运算

快乐打工仔 分类:实例代码

JavaScript加减乘数运算属于前端实例代码,有关更多实例代码大家可以查看

分享一段代码实例,它实现了简单的加减乘数运算功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

JavaScript加减乘数运算,这样的场景在实际项目中还是用的比较多的,关于JavaScript加减乘数运算就介绍到这了。

回复

我来回复
  • 暂无回复内容