计算器功能不起作用 - Javascript

时间:2015-10-23 20:29:38

标签: javascript jquery html

我正在构建一个计算器,其javascript功能因某些原因无效。我检查了我的代码,我确信我有正确的语法和一切。

继承我的codepen的链接 http://codepen.io/theMugician/pen/ojEEGr

这是html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="calculator" class="container">
  <div id="screen" class="text-right">
    0
  </div>
  <div id="controls">
    <div id="circle">
      <div class="button equals">
        =
      </div>
    </div>
    <div style="margin-top: ;" class="buttonRow text-center">
      <div class="button">
        AC
      </div>
      <div class="button">
        CE
      </div>
      <div class="button">
        %
      </div>
      <div class="button">
        /
      </div>
    </div>
    <div class="buttonRow text-center">
      <div class="button">
        7
      </div>
      <div class="button">
        8
      </div>
      <div class="button">
        9
      </div>
      <div class="button">
        *
      </div>
    </div>
    <div class="buttonRow text-center">
      <div class="button">
        4
      </div>
      <div class="button">
        5
      </div>
      <div class="button">
        6
      </div>
      <div class="button">
        +
      </div>
    </div>
    <div class="buttonRow text-center">
      <div class="button">
        1
      </div>
      <div class="button">
        2
      </div>
      <div class="button">
        3
      </div>
      <div class="button">
        -
      </div>
    </div>
  </div>
</div>

这是java脚本

var entries = [];
var total = 0;
var temp = '';

$(".button").on("click", function() {
 	var val = $(this).text();

  // Got a number, add to temp
  if (!isNaN(val) || val === '.') {
    temp += val;
    $("#screen").val(temp.substring(0,10));
    
  // Got some symbol other than equals, add temp to our entries
  // then add our current symbol and clear temp
  } else if (val === 'AC') {
    entries = [];
    temp = '';
    total = 0;
    $("#screen").val('')

  // Clear last entry
  } else if (val === 'CE') {
    temp = '';
    $("#screen").val('')
 
  // Got the equals sign, perform calculation
  } else if (val === '=') {
  	entries.push(temp);
    // Definitely not the most elegant
    var newTotal = eval(entries.join('').substring(0, 10))
    $("#screen").val(newTotal);
		entries = [];
    temp = '';
    
  // Push operators
  } else {
    entries.push(temp);
    entries.push(val);
    temp = '';
  }
});

2 个答案:

答案 0 :(得分:1)

两个主要错误:

  1. 您必须.trim()按钮的文字值。因为通常情况下,他们的文字就像       AC      。所以代码修复:

    var val = $(this).text().trim();
    
  2. 您尝试按#screen更改.val文字,<input>元素仅 。相反,请使用$("#screen").text()

  3. 修复了包含一些有用调试消息的代码:http://jsfiddle.net/Darker/hrfeabjy/

答案 1 :(得分:1)

有一些问题,但是adeneo prettey很多都是主要问题。我编辑了您的codepen,请查看下面的链接。包含通过数据属性确定按钮值的更好方法(参见Juhana的评论)。

<div class="button" data-val="%">

然后在js中访问它:

var val = $(this).data("val");

我还改变了&#34; =&#34;的zindex。按钮圈使整个按钮可以点击,而不仅仅是上半部分。

http://codepen.io/anon/pen/Yyegzq