开发者

How to use a var that has been set in one html file in another html file?

开发者 https://www.devze.com 2023-02-09 20:37 出处:网络
I have a html page that sets a value onclick using a js function. I need to use this value in开发者_Go百科 another html page. I am unable to do it. It seems to reset the value when I use the value fro

I have a html page that sets a value onclick using a js function. I need to use this value in开发者_Go百科 another html page. I am unable to do it. It seems to reset the value when I use the value from the second page. The .js file has been included in both the html pages. How do I retain the set value across multiple html pages?


Within JavaScript itself, you cannot keep track of variables across page loads. To pass the variable from one page to another, you will need to use a 'man in the middle' to help out. Either a cookie, or a query string.

A cookie would work great! I won't go into specifics of setting/getting cookies in JavaScript as there is excellent documentation here: http://www.w3schools.com/JS/js_cookies.asp

Using those set and get methods (which of course you could customise to suit your needs):

First page:

var yourVariableToSave = 'I like cheese and crackers';
var numDays = 10;    //How long the cookie should last.
setCookie('SomeCookieName', yourVariableToSave, numDays);

Second page:

var yourVariable = getCookie('SomeCookieName');
alert(yourVariable);    //Displays 'I like cheese and crackers'

If you only want the cookie to last the duration of the current settings, you can modfy the setCookie function to not specify an expiry date.

If this is for a single request, a query string might be useful. To do this, you could append ?someQueryStringName=YourVariableValue to all links on the page, or inject the query string when the user is about to load another page. I won't go in depth with this option as I suspect a cookie may be a bit better.

0

精彩评论

暂无评论...
验证码 换一张
取 消