使用本地存储的变量来clearInterval

时间:2017-11-05 19:20:14

标签: javascript jquery html if-statement local-storage

我在页面上有一个按钮,当点击它时链接到另一个页面并将本地存储的变量设置为" true"。在新页面上,我有一个使用setInterval函数隐藏的div。如果变量设置为" true"我希望setInterval不会触发。

HTML:

<!--Page 1-->
<a href="page2.html">
  <div id="view" class="mainButton">view progress</div>
</a>

<!--Page 2-->
<div id="showChart">
  <p>view progress</p>
</div>

<div id="containChart">
  <!--Chart-->
  <canvas id="theChart" width="400" height="400"></canvas>
  <!--Back to Profile-->
  <div id="closeChart">close</div>
</div>

JavaScript(一些jQuery):

displayChart();

var timeIt;

function displayChart() // Hides chart shortly after loading of page.
{
  var timeIt = setTimeout(function()
  {
    document.getElementById("containChart").style.display = "none";
  }, 0.1);

  var condition = localStorage.quickAccess;
  if(condition === true)
  {
    clearTimeout(timeIt);
  }
}

// Keep chart displayed if clicked.
$("#view").click(function()
{
  localStorage.quickAccess = true;
});

// Show Progress Chart.
$("#showChart").click(function()
{
  $("#containChart").css("display", "block");
  console.log(localStorage.quickAccess); // Logs correctly: if "#view" was clicked returns "true".
});

// Hide Progress Chart.
$("#closeChart").click(function()
{
  $("#containChart").css("display", "none");
});

2 个答案:

答案 0 :(得分:1)

localStorage将您放入其中的任何内容存储为字符串。

因此localStorage.quickAccess === true"true" != true返回false。

一个简单的替代方法是localStorage.quickAccess === "true"

答案 1 :(得分:0)

您可以在setTimeout处理程序中测试“condition”的值,也许可以用这种方式覆盖它。但我也注意到你的超时时间是“0.1”,这在JS中意味着1/10毫秒。如果你的意思是1/10秒,请使用100。