我正在尝试将操作员按钮动态添加到我的计算器,但我只是运气不好。我已经创建了动态创建数字和操作员按钮的函数。数字已成功创建,但一旦我尝试添加运算符,就没有任何反应。我正在尝试使用 for-in 循环在我的括号按钮和求值按钮之间添加运算符。似乎当我在运算符之前创建评估按钮时,评估按钮已成功创建,但运算符却没有。如果我在评估按钮之前移动代码以创建运算符 ,则两者都不会出现。我相当确定问题出在我的 for-in 循环中,但我不太确定在哪里。非常感谢任何和所有帮助/指导!
var opsData = {
add: {
precedence: 1,
name: 'add',
operation: function (a, b) {return a + b;},
output: function (a, b) {return a + ' + ' + b;},
buttonHTML: '+'
},
subtract: {
precedence: 1,
name: 'subtract',
operation: function (a, b) {return a - b;},
output: function (a, b) {return a + ' - ' + b;},
buttonHTML: '-'
},
multiply: {
precedence: 2,
name: 'multiply',
operation: function (a, b) {return a * b;},
output: function (a, b) {return a + ' * ' + b;},
buttonHTML: '*'
},
divide: {
precedence: 2,
name: 'divide',
operation: function (a, b) {return a / b;},
isInvalidInput: function (a, b) {return b == 0 ? 'division by 0' : false;},
output: function (a, b) {return a + ' / ' + b;},
buttonHTML: '/'
}
}
$.fn.addButton = function(html, className, onclick) {
$('<button />', {
html: html,
'class': 'button ' + className,
click: onclick
}).appendTo(this);
return this;
}
var addOperatorButton = function(op, click) {
$operators.addButton(op.buttonHTML, 'operator ' + op.name, function(e) {
click.call(this, e);
$currentCalc.text(inputStack.getCalculationString());
$collapsedCalc.text(inputStack.getCalculationString(true));
$input.text(inputStackgetPartialResult());
$input.data({clearOnInput: true});
});
};
var getInput = () => {
var input = $input.text();
return input.match(/error/i) ? 0 : parseFloat($input.text())
}
for (var i in opsData) {
(function(i) {
if (!opsData.buttonHTML[i]) return;
addOperatorButton(opsData[i], () => {
inputStack.push(getInput(), new Operation(opsData[i]));
})
}(i))
}
我的完整代码笔的链接在这里:https ://codepen.io/tazmancooks/pen/PoNwGMX
如果我的问题没有得到很好的表达,我深表歉意,总的来说,我对 jQuery 和 Javascript 还是很陌生。
小怪兽爱吃肉
幕布斯6054654
相关分类