1

我正在用 JavaScript 和 HTML 制作一个在线游戏(一个非常简单的游戏,这是我的第一个)。它工作正常,但有一个大问题。我希望每当单击特定图像时,变量得分的值都会增加 10。这是我使用的代码:

var score = 0;
function addScore() {
var test = parseInt(score);
var score = parseInt(test) + 10;
document.getElementById("score").innerHTML=score; }

以及我想要具有功能的图像:

<img src='mole.png' alt='mole' onclick='addScore()' />

有什么问题,我该如何解决?

4

3 回答 3

1

You're shadowing the external score variable with the one of your function. And this internal variable is each time reset to 0.

Instead of parsing the score each time, simply initialize it once :

var score = 0;
function addScore() {
     score += 10;
     document.getElementById("score").innerHTML=score;
}
于 2013-05-18T07:19:15.633 回答
1

你可以通过改变这个让你的生活变得更简单:

1. Don't use the same varibale name in globally & locally.
2. Removing the `parseInt()` method as score is already an Integer.

所以你的最终脚本应该是:

var score = 0;
function addScore() {
     score += 10;
     document.getElementById("score").innerHTML=score;
}
于 2013-05-18T07:30:35.057 回答
0

You declared score Globally and locally.So the value is not updating

var score = 0;
function addScore() {
var test = parseInt(score);
score = parseInt(test) + 10;
document.getElementById("score").innerHTML=score; }  
于 2013-05-18T07:19:40.527 回答