我正在使用此代码作为我正在制作的游戏的一部分。但为了找出导致此错误的原因,我将这部分代码放入了一个新的 html 文档中。 我正在尝试使用此代码:
<html>
<script type="text/javascript">
Difficulty = Normal
function ChangeGameMode()
{
alert (Difficulty + ' game started ');
}
</script>
<button type="button" class="StartButton" onclick="ChangeGameMode()">Start</button>
</html>
当我单击按钮时,我没有收到警报。什么也没发生。
但是如果我不在警报中使用难度变量 - 即:
alert ('Normal' + ' game started ');
然后,当我将其用于警报时,它确实有效。 我完全不知道是什么原因造成的,因此我一直在拔头发。任何帮助将不胜感激。
最佳答案
您尚未正确定义Difficulty
变量。您需要为其分配一个有效值。 Normal
不是有效的 JavaScript 值。您需要将其用引号引起来:
<html>
<script type="text/javascript">
var Difficulty = 'Normal';
function ChangeGameMode() {
alert (Difficulty + ' game started ');
}
</script>
<button type="button" class="StartButton" onclick="ChangeGameMode()">Start</button>
</html>
关于javascript - 无法在函数内的警报中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101322/