1

这是我的代码:

<html>
<head>
<title>My Game Title Goes Here!</title>
<script type="text/javascript">
function startGame(){
    document.getElementById("2").innerHTML = ('Testing!');
}
document.body.onload = keyListener(){
    document.getElementById("1").onkeypress = startGame;
}
</script>
</head>
<body>
<div class="title" name="Game Title" id="0">Game Title</div>
<div tabindex="0" class="gamecontainer" name="Game Container" id="1">
Press any key to start.
</div>
<div class="gamemonitor" name="Game Monitor" id="2">
Game Monitor:
</div>
</body>
</html>

我没有像我期望的那样工作(我使用的是谷歌浏览器)。

它只有在我直接运行时才有效,如下所示:

<div tabindex="0" class="gamecontainer" name="Game Container" id="1" onkeypress="document.getElementById('2').innerHTML = ('Testing!')">
Press any key to start.
</div>
<div class="gamemonitor" name="Game Monitor" id="2">
Game Monitor:
</div>

我检查了我的代码无数次,我找不到任何明显的错误,如拼写错误或任何东西。如果这是问题所在,那么我很抱歉浪费了你的时间,但这真的让我很烦。

4

5 回答 5

2

元素 ID 不能以数字开头,这几乎肯定会导致您的问题。将 HTML 和 JS 中的 ID 更改为以字母开头。

其次,这keyListener条线应该是这样的:

window.onload = function(){
    document.getElementById("newId").onkeypress = startGame;
}
于 2012-06-07T15:22:09.380 回答
1

Change :

document.body.onload = keyListener(){
    document.getElementById("1").onkeypress = startGame;
}

To:

document.body.onload = function(){
    document.getElementById("1").onkeypress = startGame;
}

And, id shouldn't begin with a number as it's an invalid HTML.
Chrome seems to overcome this mistake, but it shouldn't be used.

And move the code to the the <body> tag or use window.onload
document.body doesn't exist above the <body>.

于 2012-06-07T15:24:05.537 回答
1

document.body没有onload财产。应该是window.onload

window.onload = function(){
    document.getElementById("1").onkeypress = startGame;
}

演示:http: //jsfiddle.net/9khng/

于 2012-06-07T15:27:52.477 回答
0

我认为身份证不能以数字开头。

于 2012-06-07T15:22:48.750 回答
0

尝试修复您的“onkeypress”属性。你的报价搞砸了。

onkeypress="document.getElementById('2').innerHTML = ('Testing!')"
于 2012-06-07T15:25:22.247 回答