简体   繁体   English

防止每次加载页面时刷新JavaScript

[英]Prevent JavaScript to be refreshed every time the page is loaded

I have the following code: 我有以下代码:

<script type="text/javascript">

var Value = new Date();
var min = Value.getHours();

setTimeout ("Timeout()", 1);

function Timeout ()
{
    for (var i = 0; i <= 15; i++) {
    var x = document.getElementsByClassName("d")[i];
    x.innerHTML = (min + ":" + "0" );
    };
    min--;
    setTimeout ("Timeout()", 1000);
}

</script>
<p class="d"></p>

Now my problem is that every time I refresh the page the variable gets reset. 现在的问题是,每次刷新页面时,变量都会重置。 Is there a way to set the variable once for a certain amount of time, so it doesn't get reset? 有没有一种方法可以在一定时间内设置一次变量,这样就不会重置? Thanks 谢谢

There are several ways to achieve this. 有几种方法可以实现此目的。 You could use cookies to save the variable - see here for more info and check upon the next request, if a cookie was set. 您可以使用cookie来保存变量- 有关更多信息 ,请参见此处,并在下一个请求中检查是否设置了cookie。

Other than that, you could also utilize URL parameters to retain state 除此之外,您还可以利用URL参数来保留状态

location.hash = your_var;

And check upon the next request, if location.hash has been set. 并检查下一个请求,是否已设置location.hash There are several other possibilities for that, I only showed you two ways to do such a thing. 这样做还有其他几种可能性,我只向您展示了两种执行此操作的方法。

Guess the easiest way would be using cookies, you can achieve that easily using jQuery cookie plugin, this one for example , which makes the saving as easy as: 猜猜最简单的方法是使用cookie,您可以使用jQuery cookie插件轻松实现这一点,例如 ,它使保存变得简单:

$.cookie("example", "foo");

and reading: 和阅读:

$.cookie("example")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM