Using Global Variables between multiple functions in JQuery?

两盒软妹~` 提交于 2019-12-13 05:19:10

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/25110290/using-global-variables-between-multiple-functions-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!