2014-09-30 72 views
-1

我有这个非常简单的计算器。本质上,我想将小复活节彩蛋放入代码的功能中。这是我的codepen以显示我迄今为止所做的。我已经评论过我没有奏效的尝试。我知道codepen不显示警报,所以我已经尝试过他们的实时页面,警报仍然不起作用。这里是JavaScript当显示数字时附加警报()

// Variables 

var appendDigits = false 
var prevResult = 0 
var op = "=" 

//Functions 

function clearDisplay() { 
document.calculator.display.value = 0 
prevResult = 0 
appendDigits = false 
op = "=" 
} //clear 

function doOp(newop) 
{ 
var newArg =eval(document.calculator.display.value) 
if (op == "+") { 
    prevResult = prevResult + newArg   
} 
else if (op == "-") { 
    prevResult = prevResult - newArg   
} 
else if (op == "/") { 
    prevResult = prevResult/newArg 
} 
else if (op == "*") { 
    prevResult = prevResult * newArg 
} 
else if (op == "=") { 
    prevResult = newArg 
} 
// else if (newArg == 42) { 
// alert("You have found the meaning of life, the universe, and everything."); 
// } 
    else { 
     prevResult = newArg 
    } 
    document.calculator.display.value = prevResult 
    appendDigits = false 
    op = newop 
} //doOp 

function digit(dig) { 
    if (appendDigits) { 
     document.calculator.display.value += dig 
    } 
    else { 
     document.calculator.display.value = dig 
     appendDigits = true 
    } 
} 

//fuction meaning(document.calculator.display.value) 
//{ 
// if ("newArg" == "42") { 
// alert("You have found the meaning of life, the universe, and everything."); 
// } 
// else { 
// prevResult = newArg 
// } 
//} 
+0

我在codepen上的JS代码的顶部添加了一个“alert('hello')”,并且警报在最新的chrome中正确弹出。 http://codepen.io/anon/pen/Kxekc – Will 2014-09-30 19:11:21

+0

你没有在注释代码中正确拼写功能。这可能是你的问题吗? – 2014-09-30 19:17:23

回答

0

利用这计算器显示的值转换为int:

else if (parseInt(newArg) == 42) { 
    alert("You have found the meaning of life, the universe, and everything."); 
} 
0

您需要添加外你检查的if/else if循环支票“运”另有其中一个“if op ==”选项将评估true并结束循环。

你可以把它分配newArg之后:

var newArg =eval(document.calculator.display.value) 

    if (newArg == 42) { 
    alert("You have found the meaning of life, the universe, and everything."); 
    } 
0

如果可能的话,尽量不要使用eval语句在JS。这被认为是不好的做法。
见:Why is using the JavaScript eval function a bad idea?

演示:http://codepen.io/anon/pen/Kxekc

而是使用下面你输入转换为数字:

var newArg = parseInt(document.calculator.display.value,10); 

    if (newArg == 42) { 
    alert("You have found the meaning of life, the universe, and everything."); 
    } 

底部的功能也输错: //机能的研究意义( document.calculator.display.value)