如何在会话中使计数变量持久化? [英] How do I make a count variable persistent across sessions?

查看:49
本文介绍了如何在会话中使计数变量持久化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态页 / story ,其中有一个显示make your choice的按钮,由 / choice 。在 / choice 我在标题中有这个脚本

I have a static page /story that has a button that says "make your choice" which is handled by /choice. In /choice I have this script in the header

var count = 0;

function writeToStorage()
{ 
  var user = "user" + count;
  count++;
  localStorage.setItem("chooser", user);

  document.getElementById("form_chooser").value = user;  
};

因此,每次调用 / choice 通过 / story count重置为零。如何使计数持久化,以便每次调用 / choice 时使用当前值?

So, every time /choice is called by /story "count" is reset to zero. How do I make "count" persistent so that each time /choice is called the current value is used?

我问了一个之前的问题为此,但我认为不清楚我想做什么,答案集中在函数 writeToStorage()。确实,如果我在一个会话中多次调用 writeToStorage

I asked a previous question for this, but I think it was not clear what I wanted to do and the answers concentrated on the function writeToStorage(). It is true that if I call writeToStorage several times in one session

writeToStorage();
writeToStorage();
writeToStorage();

count增加但是只要 / choice 运行计数重置为零。我想数坚持下去。谢谢。

"count" is incremented but as soon as /choice is run the count is reset to zero. I would like "count" to persist. Thanks.

推荐答案

沿着这些方向扫描:

    var count = localStorage.getItem("count") || 0;

function writeToStorage() {

    count++;
    localStorage.setItem("count", count);
    document.getElementById("form_chooser").value = "user" + count;

};

因此,第一行获取当前本地存储计数,如果未定义,则为0(如果计数从未存储,用户第一次来到你的页面),然后你增加计数并保存它。然后在元素中写入当前计数。

So, first line gets the current local storage count or 0 if it's undefined ( if the count was never stored, the user camed for the first time to you're page ) , then you increment the count and save it . Then write the current count in the element .

这篇关于如何在会话中使计数变量持久化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆