【问题标题】:How to implement localstorage for current open tab?如何为当前打开的标签实现本地存储?
【发布时间】:2020-03-27 20:34:56
【问题描述】:

我关注此link 将数据存储在我的浏览器中以获取单选按钮。问题是如果我在另一个选项卡中打开相同的 url,则单选按钮会按照上一个选项卡进行选择。

功能是 - 提交按钮重定向到另一个页面。所以,我需要的只是当前打开的特定标签和特定链接的本地存储。

我正在使用的代码

<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes" />
<title>Save state of checkbox on refresh using JavaScript</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/custom.css" rel="stylesheet" />
<style type="text/css">
</style>
</head>
<body>

<ul class="list-group">
      <li class="list-group-item"><input type="checkbox" class="save-cb-state" name="mycheckbox" value="asdf"> Must I save my state?</li>
      <li class="list-group-item"><input type="checkbox" class="save-cb-state" name="anothercheckbox" value="1"> Try and save this</li>
      <li class="list-group-item"><input type="checkbox" class="save-cb-state" name="mycheckbox2" value="qwer"> This can be saved as well.</li>
    </ul>  
<script>
// Avoid scoping issues by encapsulating code inside anonymous function
(function() {
 // variable to store our current state
  var cbstate;

  // bind to the onload event
  window.addEventListener('load', function() {

    // Get the current state from localstorage
    // State is stored as a JSON string
    cbstate = JSON.parse(localStorage['CBState'] || '{}');

    // Loop through state array and restore checked 
    // state for matching elements
    for(var i in cbstate) {
      var el = document.querySelector('input[name="' + i + '"]');
      if (el) el.checked = true;
    }

    // Get all checkboxes that you want to monitor state for
    var cb = document.getElementsByClassName('save-cb-state');

    // Loop through results and ...
    for(var i = 0; i < cb.length; i++) {

      //bind click event handler
      cb[i].addEventListener('click', function(evt) {
        // If checkboxe is checked then save to state
        if (this.checked) {
          cbstate[this.name] = true;
        }

    // Else remove from state
        else if (cbstate[this.name]) {
          delete cbstate[this.name];
        }

    // Persist state
        localStorage.CBState = JSON.stringify(cbstate);
      });
    }
  });
})();
</script>
</body>
</html> 

【问题讨论】:

  • 问题是,在标签之间保持相同的值还是每个标签都有自己的存储空间?有点不清楚如果我在另一个选项卡中打开相同的 url 是什么意思,单选按钮是根据上一个选项卡选择的。我需要的是本地存储当前打开的特定选项卡和特定链接。
  • @LawrenceCherone 首先打开产品页面并选择了一些单选按钮并尝试使用提交按钮启动产品,但在页面加载后它们会显示一些警告消息,例如“某些复选框没有选定”。现在我关闭了选项卡并在另一个新选项卡中打开了相同的链接。这次我用相同的链接打开了一个新的 freash 页面(但相同的链接 - Woocommerce 产品页面) - 由于 localstorage,这里有些复选框被打勾。
  • 使用 sessionStorage 而不是 localStorage。 sessionStorage 仅对该会话有效。关闭选项卡后,存储在浏览器会话中的值将丢失。

标签: javascript jquery local-storage session-cookies browser-cache


【解决方案1】:

您应该能够使用 sessionStorage 而不是 localStorage 来管理它。在此处了解有关差异的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

【讨论】:

    【解决方案2】:

    只需将内容 localstorage 更改为 sessionStorage。以下是此问题的更新代码和解决方案(如何为当前打开的选项卡实现本地存储?)。 答案是:

    <script>
    // Avoid scoping issues by encapsulating code inside anonymous function
    (function() {
     // variable to store our current state
      var cbstate;
    
      // bind to the onload event
      window.addEventListener('load', function() {
    
        // Get the current state from localstorage
        // State is stored as a JSON string
        cbstate = JSON.parse(sessionStorage['CBState'] || '{}');
    
        // Loop through state array and restore checked 
        // state for matching elements
        for(var i in cbstate) {
          var el = document.querySelector('input[name="' + i + '"]');
          if (el) el.checked = true;
        }
    
        // Get all checkboxes that you want to monitor state for
        var cb = document.getElementsByClassName('save-cb-state');
    
        // Loop through results and ...
        for(var i = 0; i < cb.length; i++) {
    
          //bind click event handler
          cb[i].addEventListener('click', function(evt) {
            // If checkboxe is checked then save to state
            if (this.checked) {
              cbstate[this.name] = true;
            }
    
        // Else remove from state
            else if (cbstate[this.name]) {
              delete cbstate[this.name];
            }
    
        // Persist state
            sessionStorage.CBState = JSON.stringify(cbstate);
          });
        }
      });
    })();
    </script>
    
    

    特别感谢@Jacob Nelson

    【讨论】:

      猜你喜欢
      • 2014-05-07
      • 1970-01-01
      • 2017-04-25
      • 2014-01-14
      • 1970-01-01
      • 2012-01-08
      • 2017-03-17
      • 1970-01-01
      • 2018-03-03
      相关资源
      最近更新 更多