我写了简单的计算器在JS & jQuery和我遇到了奇怪的行为。在下面的代码中,您会看到变量公式,其中包含计算器上按下的每个数字。然后我使用eval()
来评估。为什么方程的值在最后没有定义?
问题是,方程变量的这个值是你所期望但不确定末,而不能找出原因。
整个项目位置:http://codepen.io/ketus/full/XmYRoV/
感谢您的帮助提前!
PS .:我知道关于eval()
的一般意见。它只用于测试,所以我可以移动。我将在解决undefined问题后实施我自己的解决方案。
$(document).ready(function() {
var equation = '';
var input = $('h2[data-value]');
var info = $('#info');
//get keys
var keys = $('.key').filter(function() {
return $(this).data('key');
}).get();
//get operators
var operators = $('.operator').filter(function() {
return $(this).data('operator');
}).get();
//Clearing input
$('.clear').click(function(){
equation = '';
input.html('');
info.html('');
});
//user press keys, check if correct after each click
$('.key').click(function(){
equation += $(this).data('key');
//evaluateEquation();
input.html(equation);
});
//showing result
$('a[data-calc]').click(function(){
input.html(eval(equation.toString()));
});
// rules for equation to be correct
//function evaluateEquation() {
//}
function calculate(){
if(equation.length > 0){
return eval(equation);
} else {
info.html('Enter something!');
return '';
}
}
});
没有'数据key'为等于按钮 –