如何在jQuery中为每个会话设置一个值?

时间:2018-03-19 18:38:09

标签: javascript jquery html

我在jquery中生成一个随机数,我希望这个值不会在每个会话中更改。这意味着,每次刷新页面时都不应更新该值。

<p class="remaining-memberships"><span>XX</span>/p>

这是我目前的代码:

  var minMember = 10;
  var maxMember = 50;

  var randomNumber = randomNumberFromRange(minMember, maxMember);

  function randomNumberFromRange(min,max)
  {
      return Math.floor(Math.random()*(max-min+1)+min);
  }

  var yetVisited = localStorage['visited'];
  var setRandomMember = randomNumber;

  if (!yetVisited) {
    // open popup
    localStorage['visited'] = "yes";
    $('.remaining-memberships span').html(randomNumber);
  }
  else {
  }

如何正确设置我的if else代码,以便$(&#39; .remaining-memberships span&#39;)中的值只有在页面尚未访问且已访问过时才会更改,价值必须保留。

感谢任何帮助。感谢

3 个答案:

答案 0 :(得分:1)

尝试从本地存储中获取值/对象,如果它是空的,则运行您的函数,然后存储在localStorage中。

我已将其更改为存储为JSON,可以在检索时对其进行解析,因为它允许您使用randomNumbervisited存储访问对象值(不确定你是否想要更晚)。

<script>
  var visit = localStorage.getItem("visit");

  // new visit
  if (!visit) {
    var minMember = 10;
    var maxMember = 50;

    function randomNumberFromRange(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    }

    var randomNumber = randomNumberFromRange(minMember, maxMember);

    visit = {
      visited: 'yes',
      randomNumber: randomNumber
    };

    localStorage.setItem('visit', JSON.stringify(visit));
  } else {
    visit = JSON.parse(visit)
  }

  $('.remaining-memberships span').text(visit.randomNumber);

</script>

未经测试但应该可以使用。

答案 1 :(得分:1)

您可以将随机存储在localStorage中,如下所示:

  var minMember = 10;
  var maxMember = 50;

  var randomNumber = randomNumberFromRange(minMember, maxMember);
  localStorage['myRandom'] = randomNumber;

答案 2 :(得分:0)

为什么不用随机标志将随机数存储在localStorage中?

var minMember = 10;
var maxMember = 50;

var randomNumber = randomNumberFromRange(minMember, maxMember);
function randomNumberFromRange(min,max)
{
  return Math.floor(Math.random()*(max-min+1)+min);
}

var yetVisited = localStorage['visited'];
var setRandomMember = randomNumber;

if (!yetVisited) {
   // open popup
   localStorage['visited'] = "yes";
   localStorage['randomNumber'] = randomNumber;
   $('.remaining-memberships span').html(randomNumber);
}
else {
   $('.remaining-memberships span').html(localStorage['randomNumber']);
}