简体   繁体   中英

How do I change a variables data value in external .js file?

So I'm working on a game and I'm trying to make a Level Selector right now. However I only want players to be able to play on levels that they've beaten. So I have a .js file labeled "ELD.js" and it contains:

    var Levels = 0;

I don't really care how(in aspects of programing type). But I want to be able to change the "Levels" data value every time I win a level. Each level has it's own individual html file and all of the level files are in the same file as the "ELD.js" file.

I've looked for an answer to this but none of them seem to match what I need.

And while I'm on this subject (correct me if I'm wrong) but I can simply test for the "Levels" data value using this right?

    <script type="text/javascript" src="ELD.js"></script>
    <script>
    if(Levels =< X)
    {
         }
    </script>

X simply stands for an undefined number that I will choose later.

You can build your javascript files as a class and assign that variable to the class for example:

class GameLevel {
    constructor (level) {
        this.level = level;
    }

    get_level () {
        return this.level;
    }

    set_level (level) {
        this.level = level;
    }
}

Then throughout the game you have your object:

var cur_level = 1;
var level = new GameLevel (cur_level);

Then after a game is beaten you simply call

level.set_level (++cur_level)

I believe you can even just say level.level = cur_level + 1;

EDIT

Also to pass you because you want to pass your javascript data to another html file there is also a way to that as well. You can use this logic:

  1. Open the new level in a new tab
  2. Pass the data
  3. Close the current window and focus on the new opened window

This is like a weird way to do it but I belive it can work :) to do this you run the following code:

var newLevel        = window.open (<URL TO HTML FILE>, '_blank');

// passing thejavascript data
newLevel.new_level  = level.get_level ;  // This is the data to pass or you can use the variable you had declared

// focus on new window
newLevel.focus ();

// close current window
window.close ();

Edit

and then in all your html file you can get the value of your new level data using window.new_level When the window is opened it will have the value you passed set.

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