2016-09-23 132 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); 
}