如何将localStorage对象设置为变量

时间:2016-05-20 17:35:10

标签: javascript local-storage

我想使用localStorage对象使用JavaScript制作应用程序,以便我可以存储信息,以便下次打开文件时,之前存储的信息仍然存在。我的目标是你在网站上呆了多长时间。怎么可以使用localStorage.setItem("example", "variable")所以我可以用它作为时钟的计数器?这是我的测试代码之一:

<!DOCTYPE html>
<html>
<title>Tracking Time</title>
<style>
#time {
    font-size: 250%
}
</style>
<center>
<body>
<h1><font face="fantasy">The Time You Have Had This Tab Open</font></h1>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<h1 id="time"><font face="impact" size="10">00:00:00:00:00:00</font></h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>

// Update Count

setInterval(function () {
 localStorage.setItem("sec", 0);

}, 1000)

//


// Update Text

setInterval(function (){
$("#time").text( + " year(s) " +  + " month(s) " +  + " day(s) " +  + " hour(s) " +  + " minute(s) " + localStorage.getItem("sec") + " second(s)")
}, 1)
</script>

</body>
</center>
</html>

很抱歉它不完整,但我需要帮助。我可以用它作为变量吗?请举个例子。谢谢!

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是在本地存储中设置某种“时间”属性(如果不存在)。

if (localStorage.getItem('time') === null) {
  localStorage.setItem('time', 0);
}

然后在循环期间,您可以增加本地存储中保存的时间。

var intervalTime = 1000;
setInterval(function() {
  // localStorage saves as strings so lets make it an integer
  var totalTime = parseInt(localStorage.getItem('time'));
  localStorage.setItem('time', totalTime + intervalTime);
}, intervalTime);

这将节省用户在您网站上花费的总毫秒数。然后,您可以使用这些毫秒来显示他们在网站上的时长。

var totalMilliseconds = parseInt(localStorage.getItem('time'));
var totalTime = new Date(totalMilliseconds);
var hours = totalTime.getHours();
var minutes = totalTime.getMinutes();
var seconds = totalTime.getSeconds();
相关问题