[英]Alert Message Button
Trying to get the button called, "check" to show the var result from the answer prompt1 function. 试图获取名为“ check”的按钮,以显示答案提示1函数的var结果。 For whatever reason when I run the code nothing happens when the button is clicked.
无论出于何种原因,当我运行代码时,单击按钮都不会发生任何事情。 I know the calculation is right because, when I set the answer button to give the intended alert, it works properly.
我知道计算是正确的,因为当我设置答案按钮以发出预期的警报时,它可以正常工作。 How do I get the second button to display my results entered?
如何获得第二个按钮以显示输入的结果?
<!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>
result
is declared in answerPrompt1
, which gives it local scope (ie it isn't visible outside that function). result
在answerPrompt1
中声明,这为它提供了局部范围(即,在该函数外部不可见)。 move the declaration to just before the function: 将声明移到函数之前:
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>
You should change your result
variable in a way that it can be accessible to both functions answerPrompt1()
and showResult()
You can have a clear understanding about how javascript scope works from here . 您应该更改
result
变量,使它可以同时被answerPrompt1()
和showResult()
函数访问。您可以从这里对javascript范围的工作方式有一个清晰的了解。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.