jq 函数引用变量,在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:

Put the data in a cookie which you can read from each successive page when that page loads.

Put the data in a browser local storage which you can read with javascript from each successive page when that page loads (recommended option).

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值