Global variable with jquery

I have a js file test.js that contains the global variable global_var and a function fn1() that changes the global_var variable:

 var global_var="initial_value"; function fn1(){ global_var="Value1"; alert("global_var="+global_var); } 

then I execute fn1() from my page1.html, which sends me to page2.html:

 <li><a href="page2.html" onclick='fn1();'></a></li>//this returns "global_var=Value1" 

Then in page2.html I want to use the global_var variable, but the continuous global_var does not change, it is "initial_value" !!

 <script src="test.js"></script> <script> $('#mypage').live('pageshow', function(event) { alert(global_var); //this returns "initial_value"!!! }); </script> 
+4
source share
4 answers

You do not call the function on page 2. Each time you load to another page, your JS will reset ... Save it to SESSIONS or locally, for example, if you want to keep it alive!

+2
source

Each time a new page loads, javacript is reinitialized and therefore any change to the variable is lost. You can save this value in a cookie and get it on page2

page 1

 var global_var="initial_value"; function fn1(){ global_var="Value1"; alert("global_var="+global_var); $.cookie('global_var', global_var); } 

page 2

 <script src="test.js"></script> <script> $('#mypage').live('pageshow', function(event) { var global_var = $.cookie('global_var'); alert(global_var); //this returns "initial_value"!!! }); </script> 

this requires this plugin https://github.com/carhartl/jquery-cookie

+3
source

JavaScript global variables in browsers are really page variables. They exist only as long as the window object that they were created exists (since all global variables are window properties). When you change pages, the old window object is destroyed and a new new one is created, so your variable no longer exists.

To save information between pages, consider:

  • Use of cookie.
  • Using HTML5 "local storage" (note that IE7 and earlier do not have this, but IE8 and higher , some mobile browsers may not).
  • Using server-side state (but it does not scale very well).
+2
source

If his question is only two pages long, you can use a simple query

Page1

 var k="initial_value"; function fn1(){ k="Value1"; // alert("k="+k); location.href='page2.html?k='+k; } 

Page2

 function querystring(key) { var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi'); var r=[], m; while ((m=re.exec(document.location.search)) != null) r.push(m[1]); return r; } <script> $('#mypage').live('pageshow', function(event) { alert(querystring('k')); }); 
0
source

Source: https://habr.com/ru/post/1402859/


All Articles