我无法在HTML页面的主体加载时加载倒数计时器。
计时器显示时没有checkInput()
的代码,但是当我添加代码的那部分时,它不起作用。我的基本目标是让用户输入状态(比如Sporcle)并继续运行直到它们达到50国家或时间耗尽。有什么想法吗?
我的代码:
<script>
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 100);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 100);
}
function UpdateTimer() {
Timer.innerHTML = TotalSeconds;
}
function searchKeyPress(e)
{
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13)
{
document.getElementById('button_1').click();
}
}
function doSomething(){
checkInput();
}
var usStates =
[
"ALABAMA",
"ALASKA",
"AMERICAN SAMOA",
"ARIZONA",
"ARKANSAS",
"CALIFORNIA",
"COLORADO",
"CONNECTICUT",
"DELAWARE",
"FLORIDA",
"GEORGIA",
"GUAM",
"HAWAII",
"IDAHO",
"ILLINOIS",
"INDIANA",
"IOWA",
"KANSAS",
"KENTUCKY",
"LOUISIANA",
"MAINE",
"MARYLAND",
"MASSACHUSETTS",
"MICHIGAN",
"MINNESOTA",
"MISSISSIPPI",
"MISSOURI",
"MONTANA",
"NEBRASKA",
"NEVADA",
"NEW HAMPSHIRE",
"NEW JERSEY",
"NEW MEXICO",
"NEW YORK",
"NORTH CAROLINA",
"NORTH DAKOTA",
"OHIO",
"OKLAHOMA",
"OREGON",
"PENNSYLVANIA",
"PUERTO RICO",
"RHODE ISLAND",
"SOUTH CAROLINA",
"SOUTH DAKOTA",
"TENNESSEE",
"TEXAS",
"UTAH",
"VERMONT",
"VIRGIN ISLANDS",
"VIRGINIA",
"WASHINGTON",
"WEST VIRGINIA",
"WISCONSIN",
"WYOMING"
];
usStatesLength=usStates.length;
score=0;
function checkInput(){
input=document.text_box_1.value;
for(i = 0;i < usStatesLength;i++)
{
if(input==v[i])
{
document.getElementById('answer').innerHTML="Correct";
score++;
}
else
{
document.getElementById('answer').innerHTML="Incorrect";
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>50 States</title>
<link rel="stylesheet" href="./Styles/Lab2.css">
</head>
<body onload="CreateTimer('timer', 6000)";>
<h1>50 States</h1>
<h3>Enter state to start timer</h3>
<script src="Lab2.js"></script>
<form>
<input type="text" id="text_box_1" value="" autofocus onkeyup="doSomething()" onkeypress="searchKeyPress(e)" >
<input type="submit" id="button_1" value="Enter" onClick="doSomething()"/>
</form>
<div id="timer" value=""/>
<div id="answer"value=""/>
</body>
</html>
答案 0 :(得分:1)
您需要更改此内容:
<body onload="CreateTimer("timer", 6000)";>
到此:
<body onload="CreateTimer('timer', 6000)";>
您需要在双引号内使用单引号,反之亦然
答案 1 :(得分:1)
您的代码中存在许多语法错误。
您不应将<h1>
和<h3>
标记放在<head>
标记中。它们属于<body>
标记。
脚本标签可以放在头部或身体中。如果他们进入头部,他们会在身体负荷之前被执行。如果它们进入正文,则在解析body标记的过程中执行它们,这样它们就可以在脚本标记之前看到正文中的任何标记。
在body
元素的开始标记中,您有:
<body onload="CreateTimer("timer", 6000)";>
这是无效的,因为你必须在双引号字符串中转义双引号。解析器将看到一个值为CreateTimer(
的onload属性,这是一个JavaScript语法错误,然后是timer
,它将忽略它作为无效属性,然后是", 600)"
HTML语法错误。
要解决此问题,您可以使用反斜杠转义计时器周围的引号,如onload="CreateTimer(\"timer\", 6000)"
中所示,或者您可以将内引号或外引号转换为单引号。
但是,如果将脚本标记移动到body标记的末尾并在脚本末尾添加对CreateTimer的调用,则可以省略onload
处理程序。