尝试获取调用按钮,“check”以显示answer 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 :(得分:0)
.as-console-wrapper { max-height: 100% !important; top: 0; }
在result
中声明,它赋予它本地范围(即在该函数之外不可见)。将声明移到函数前面:
answerPrompt1
&#13;
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);
}
&#13;
答案 1 :(得分:0)
您应该以{{1}}和result
两种功能都可以访问的方式更改answerPrompt1()
变量。您可以清楚地了解javascript范围的工作原理{{3 }}
showResult()