计算器jquery

我对jQuery有一些乐趣,我正在尝试创建一个基本的加减计算器,但是当用户添加(或减去)一个数字时,我遇到了一些问题,输入框中的前一个数字不会消失并被添加到下一个function。

我如何解决它?

这是小提琴: http : //jsfiddle.net/maniator/8v9zT/7/

这是我的javascript代码:

var calculator = { calcArea: $('
',{id: 'calcArea'}), buttons: $('
',{id: 'buttonArea'}), textArea: $('',{type: 'text', id: 'calcText', readonly: true}), calcStack: null, prevEq: null, body: $('body'), init: function(){ var self = this; self.createInterface(); $('button').click(function(e){ self.clickButton(e.currentTarget) }) }, createInterface: function(){ this.buttons.append(this.textArea); for(var i = 1; i <= 10; i++){ this.buttons.append($('

非常感谢你的帮助^ _ ^

你应该做

 html = parseInt(this.prevEq) + parseInt(html); 

 html = parseInt(this.prevEq) - parseInt(html); 

代替

 html = parseInt(html) + parseInt(this.prevEq); 

 html = parseInt(html) - parseInt(this.prevEq); 

添加时,订单不是问题。 这是你减去的时候。 (a + b) == (b + a)但是(a - b) != (b - a)

编辑

哎呀,这似乎不是你想要解决的问题。 我只是看了你的代码并解决了我看到的第一个错误。 您需要添加一个’=’按钮来显示结果并清除堆栈。 我不确定你打算在这做什么。 对我来说,继续添加和减去数字似乎是完全可以接受的。

编辑2

我重新开始并提出了一个新的解决方案

就个人而言,我会这样做:(在这里小提琴: http : //jsfiddle.net/billymoon/QWUhW/ )

 // declare global variables var result = 0, current = '', adding = true // create calculator interface $('body').append( $('
').attr({ id: 'calcArea' }).append( $('

').attr({ id: 'calcText' }).html(result), $('
').attr({ id: 'buttonArea' }).append( $('').addClass('button').text(7), $('').addClass('button').text(8), $('').addClass('button').text(9), $('').addClass('button').text(4), $('').addClass('button').text(5), $('').addClass('button').text(6), $('').addClass('button').text(1), $('').addClass('button').text(2), $('').addClass('button').text(3), $('').addClass('button').text(0), $('').addClass('button').text('+'), $('').addClass('button').text('-') ) ) ) // add click events $('button').click(function() { // if it is a plus or minus if (m = $(this).text().match(/([\+\-])/)){ // if mode is adding (+ was pressed more recently than -) // add result = result + current // otherwise result = result - current result = adding ? result + parseInt(current) : result - parseInt(current) // display result in results area $('#calcText').text(result) // reset current value current = '' // if + was pressed, adding is true else adding is false adding = m[1] == '+' ? true : false } else { // otherwise it is a number // add to current (as a string) current = current + $(this).text() // display current in results area $('#calcText').text(current) } })