计算器jquery [英] Calculator jquery
问题描述
我对jQuery有一些乐趣,我正在尝试创建一个基本的加减计算器,但是当用户添加(或减去)一个数字时,我遇到了一些问题,输入框中的前一个数字不会消失并获得添加到下一个函数。
I am having some fun with jQuery and I am trying to create a basic add and subtract calculator but I am having some issues when a user adds (or subtracts) a number, the previous numbers in the input box dont disappear and get added to the next function.
我该如何解决?
这是小提琴: http://jsfiddle.net/maniator/8v9zT/7/
这是我的javascript代码:
here is my javascript code:
var calculator = {
calcArea: $('<div>',{id: 'calcArea'}),
buttons: $('<div>',{id: 'buttonArea'}),
textArea: $('<input>',{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($('<button>',{text: (i==10?0:i), class: 'button'}))
}
this.buttons.append($('<button>',{text: '+', class: 'button'}))
this.buttons.append($('<button>',{text: '-', class: 'button'}))
this.calcArea.append(this.buttons);
this.body.append(this.calcArea);
},
clickButton: function(obj){
var html = obj.innerHTML;
var operator = false;
if(html == '+' || html == '-'){
if(this.calcStack == '+' || this.calcStack == '-' || this.calcStack == null){
alert('error cannot do that!');
return;
}
operator = true;
}
if(this.calcStack == '+'){
html = parseInt(html) + parseInt(this.prevEq);
operator = true;
console.log('adding')
}
if(this.calcStack == '-'){
html = parseInt(html) - parseInt(this.prevEq);
operator = true;
console.log('subtracting')
}
this.prevEq = this.calcStack;
this.calcStack = (operator?html:((this.calcStack!=null?this.calcStack:'') + html));
console.log('you clicked:', html, this.prevEq);
this.textArea.val(this.calcStack)
}
}
calculator.init();
非常感谢你的帮助^ _ ^
Thank you so much for your help ^_^
推荐答案
你应该这样做
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)
The order is not a problem when you're adding. It is when you're subtracting. (a + b) == (b + a)
but (a - b) != (b - a)
哎呀,这似乎不是你想要解决的问题。我只是看了你的代码并解决了我看到的第一个错误。
您需要添加一个'='按钮来显示结果并清除堆栈。我不确定你打算在这做什么。对我来说,继续添加和减去数字似乎是完全可以接受的。
Oops, this doesn't seem the problem you wanted to resolve. I just looked in your code and solved the first bug I saw. You will need to add an '=' button to show the result and clear the stack I guess. I'm not really sure what you intend to do here. To me it seems perfectly acceptable to keep adding and subtracting numbers.
我重新开始来了使用新解决方案
这篇关于计算器jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!