2016-09-23 156 views
0

试图获取被调用的按钮,“检查”以显示来自答案prompt1函数的var结果。无论什么原因,当我点击按钮时,运行代码时都不会发生任何事情。我知道计算是正确的,因为当我设置答案按钮来给出预期的警报时,它正常工作。我如何获得第二个按钮来显示我输入的结果?警报消息按钮

<!DOCTYPE html> 

<head> 

    <!-- 
     Name: Dakota Trumbull 
     Date: 
     Class: 
     Purpose: 
    --> 
    <title>Math Test</title> 





</head> 

<body> 

    <h1>Simple Math Test</h1> 

    <p>Q1: 5 + 9 = ??</p> 
     <button id = "Q1A" onclick = "answerPrompt1()">Answer</button> 
     <button id = "Q1C" onclick ="showResult()">Check</button> 

    <p></p> 

    <p>Q2: 4 * 6 = ??</p> 
     <button id = "Q2A">Answer</button> 
     <button id = "Q2C">Check</button> 

    <p></p> 

    <p>Q3: 25 - 14 = ??</p> 
     <button id = "Q3A">Answer</button> 
     <button id = "Q3C">Check</button> 

    <p></p> 

    <p>Q4: 48/3 = ??</p> 
     <button id = "Q4A">Answer</button> 
     <button id = "Q4C">Check</button> 

    <p></p> 

    <p>Q5: 26 % 6 = ??</p> 
     <button id = "Q5A">Answer</button> 
     <button id = "Q5C">Check</button> 

</body> 

<script> 



    //Q1 


    function answerPrompt1() 
    { 
     var answer1 = prompt("Enter your answer: "); 
     var convertedNum1 = parseInt(answer1, 10); 
     var result = (convertedNum1 == 14)? "You're right!" : 
      "Sorry, that's incorrect."; 
    } 
    function showResult() 
    { 
     alert(result); 
    } 

</script> 

</html> 
+0

添加answerPrompt1和showResult的来源可以帮助我们来帮助你 – gkr

+0

请其设置为一个片段或的jsfiddle。 – jcaron

回答

0

resultanswerPrompt1声明的,这使得它的本地范围(即它不是函数外可见)。只是功能前移到声明:

var result = "You have not given an answer yet"; 
 
function answerPrompt1() 
 
{ 
 
    var answer1 = prompt("Enter your answer: "); 
 
    var convertedNum1 = parseInt(answer1, 10); 
 
    result = (convertedNum1 == 14)? "You're right!" : 
 
     "Sorry, that's incorrect."; 
 
} 
 
function showResult() 
 
{ 
 
    alert(result); 
 
}
<body> 
 
    <h1>Simple Math Test</h1> 
 
    <p>Q1: 5 + 9 = ??</p> 
 
     <button id = "Q1A" onclick = "answerPrompt1()">Answer</button> 
 
     <button id = "Q1C" onclick ="showResult()">Check</button> 
 
    </p> 
 
</body>

0

你应该改变你的result变量的方式,它可以是两种功能answerPrompt1()访问,showResult()你可以对如何清醒的认识javascript作用范围从here

var result = "You have not given an answer yet"; //this variable is accessible to both functions 
function answerPrompt1() 
{ 
    var answer1 = prompt("Enter your answer: "); //this variable only accessible inside the function answerPrompt1() 
    var convertedNum1 = parseInt(answer1, 10); 
    result = (convertedNum1 == 14)? "You're right!" : 
     "Sorry, that's incorrect."; 
} 
function showResult() 
{ 
    alert(result); 
}