简体   繁体   中英

Can't use variable in alert within function

I am using this code as a part of a game I'm making. But for the purposes of finding out what was causing this bug I took the section of code into a new html document. I am trying to use this code:

<html>
<script type="text/javascript">
Difficulty = Normal
function ChangeGameMode()
{
  alert (Difficulty + ' game started ');
  }
</script>
<button type="button" class="StartButton" onclick="ChangeGameMode()">Start</button>
</html>

When I click the button, I don't get an alert. Nothing happens.

But if I don't use the Difficulty variable in the alert - ie:

alert ('Normal' + ' game started ');

Then when I use that for the alert instead, it does work. I am at conplete loss as to what is causing this and I have been pulling my hair out because of it. Any help would be appreciated.

You haven't properly defined the Difficulty variable. You need to assign it a valid value. Normal is not a valid javascript value. You need to wrap it in quotes:

<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>

正常情况必须用引号引起来:

var Difficulty = "Normal";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM