简体   繁体   中英

Using Global Variables between multiple functions in JQuery?

I want to dynamically load an image using jQuery like this:

main.js

 var slidersrc="";  //try to define global variable - not sure if this is correct

 jQuery(document).ready(function() {
     jQuery("#sliderimg").attr('src', slidersrc);
 });

 jQuery("#selection1").click(function() {
     slidersrc='wp-content/themes/*****/slide1.png';
 });

So the first time user access my website, the slider is empty. After user clicks on one of the selection areas, I set the global variable value. Then if user continues to navigate at my website to different pages, the user should be shown a slider image as a result of his selection.

However, this doesn't appear to work.

Am I correctly using the global variable in jQuery? Or is there a better way to save the user selection value in client side?

thanks!

Global variables do NOT survive from one page to the next. Each page starts an entirely new javascript context (all new global variables, functions, etc...).

If you want to save state from one page to the next, your options are:

  1. Put the data in a cookie which you can read from each successive page when that page loads.
  2. Put the data in a browser local storage which you can read with javascript from each successive page when that page loads (recommended option) .
  3. Store the data on the server and embed it in each page as it is served from the server.

You can read about how to read and write from browser LocalStorage here and here .

If you're planning on changing the slider image each time the user clicks, then perhaps you want to save an index into an image array in local storage. When the page loads, you read the current index from localStorage (or supply a default value if no value exists in local storage), then write back the current value to localStorage for the next page. If the user takes some action that causes the index to update to a new value, then you update your page and then write that new index into localStorage so the next page can read it from there and so on.

LocalStorage is a similar concept to cookies, but it's a bit easier to manage and more efficient (the data is not sent to the server with every page request).

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