如何从按钮增加java脚本中函数中的全局变量



这可能是一个愚蠢的问题,但我在这方面遇到了很多麻烦,因为我需要进行测试和分配,当用户点击正确的按钮时,我试图增加分数。然而,分数并没有增加。这是它的一个小样本。

<!DOCTYPE html>
<html>
<head>
	<meta charset = "utf-8">
	<title>Increment Button</title>
</head>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
	var score = 0;
	
	function IncrementScore()
	{
		score++;
	}
	
	console.log(score);
</script>
</body>
</html>

您有一些问题。

  1. 您可能想要从IncrementScore函数中console.log
  2. 您希望使用+= 1++递增变量

<!DOCTYPE html>
<html>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore() {
score++;
console.log(score);
}
console.log(score);
</script>
</body>
</html>

将代码更改为score += 1,并将控制台调用移到函数内部。

<!DOCTYPE html>
<html>
<head>
	<meta charset = "utf-8">
	<title>Increment Button</title>
</head>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
	var score = 0;
	
	function IncrementScore()
	{
		
		score += 1;
console.log(score);
	}
	
	console.log(score);
</script>
</body>
</html>

每次单击都会增加变量。在下一行中,赋值给变量"1"。您应该删除行

score = 1;

TL;DR:实际上score确实进行了增量,但没有通过单击处理程序打印出来

正如我在您的代码片段中所知,<script>标记中的所有脚本(包括console.log(最初都将执行一次。然后它坐在那里听事件,就像你的点击一样。然后,当您单击按钮时,会调用IncrementScore函数,它会增加score变量,但不会将其打印出来。你知道为什么吗?因为您没有告诉它这样做,(在IncrementScore处理程序中(。如果你注意到了,你会发现每次点击只打印出一个0,而不是每个0

您应该了解调用堆栈等。。要了解更多关于代码执行顺序的信息。。。修复片段可以在其他人的答案中找到,这是变量实际"不变"时的代码,每次单击都会打印出来。

<!DOCTYPE html>
<html>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore() 	{
//score++;
console.log(score);
}
</script>
</body>
</html>

最新更新