简体   繁体   中英

share variables between different html file using javascript or jquery

What is the simplest way to define and access shared variables between .html files belonging to the same project.

Thank you all,

b regards

If you intend for these to be unique for each client, you could:

  1. Store cookies
  2. Pass data as part of the request parameters

If you intend to store data permanently, you should use a server side language.

The variables you define in any JS file are accessed in exactly the same way. For example, consider the following variables.js file which you include at the top of all your pages:

var variable1 = "foo";
var variable2 = "bar";

Then, in any script that comes after you can simply refer to these variables. Consider mypage.html:

<html>
    <head>
        <script src="variables.js" type="text/javascript"></script>
        <script>
            alert(variable1); // alerts "foo"
        </script>
    </head>
    <body>
    </body>
</html>

The sessionStorage and localStorage objects will allow you to share key/string value pairs between .html files, provided they belong to the same domain. localStorage values are stored in the browser between sessions, and if the user switches browsers the values will not be carried with them; nor can the server view these values without extra code.

http://en.wikipedia.org/wiki/Web_storage

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