我想从JavaScript函数输出一个随机数,该函数将保存在cookie中并在应用程序结束时调用?
<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50)*2;
document.cookie="document.getElementById("demo").value";
</script>
<script>
var x = document.value;
document.getElementById("number").innerHTML = "x"
</script>
答案 0 :(得分:0)
这是Mozilla Document.cookie docs:
document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
alert(document.cookie);
// displays: name=oeschger;favorite_food=tripe
答案 1 :(得分:0)
查看有关Cookie的W3Schools教程。至于你的情况,这是你实现它的方式:
<!-- Start of the Application -->
<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50)*2;
// Following functions from W3Schools
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
// set a cookie "number" to the `innerHTML` of the element with Id `demo`.
setCookie("number",document.getElementById("demo").innerHTML,365);
</script>
<!-- End of the application -->
<script>
// get the value of the cookie "number" that was set earlier
var x = getCookie("number");
// Change the Id to whatever you need
document.getElementById("whatever").innerHTML = x;
</script>