I have 4 html page, page1-4. And global variable stores in js file, i want to update the variable by click yes/no on each of the webpage.
Is there a way to keep the variable ? e.g. store in webrownser or harddisk ?
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="js/counter.js"></script>
</head>
<body>
<h1>Are u in?</h1>
<!--img tag-->
<div id="yes">
<input type="button" name="yes" value="Yes">
</div>
<div id="no">
<input type="button" name="yes" value="No">
</div>
<script type = "text/javascript">
$("#yes").click(function() {
count = 1; //page2 will getC() and count += 2 and setC(count)
setC(count);
window.location.replace("page2.html");//maybe this will clear out something
});
$("#no").click(function() {
window.location.replace("page2.html");
});
</script>
</body>
————js file——————
var count;
function setC(c){
count = c;
}
function getC(){
return count;
}
You should use a
cookieto store the value across requests. You can use this jQuery plugin that make working with cookies very easy: https://github.com/carhartl/jquery-cookieHere is a simple example:
Setting the value
Getting the value
There is now no need for the global variable count. You can just use
setCandgetC. If you are interested in a slightly more involved solution, you can use AmplifyJS instead of the jQuery cookie plug-in. AmplifyJS will useHTML5 local storagewhen available and fall back to cookies if the browser does not support local storage. More info here: http://amplifyjs.com/api/store/