【问题标题】:Persisting data on the page on refresh刷新时将数据保留在页面上
【发布时间】:2018-06-24 11:38:42
【问题描述】:

我想在页面刷新之前保留目标有序列表的数据,然后在文档准备好时使用 jquery 将其添加到前面。 这是我的代码

// if an refresh event is fired
window.onbeforeunload = function(event){
  //store the messages into sessionStorage
  sessionStorage.setItem('ol', jQuery('#messages'));
  return undefined;
};
$(document).ready(function(){
  if (sessionStorage.getItem('ol')) {
  // Restore the contents of the ol (message contents)
    var ol = sessionStorage.getItem('ol');
    jQuery('#messages').html(ol);
  }
});
<div class="chat__main">

    <ol id="messages" class="chat__messages"></ol>

    <div class="chat__footer">
      <form id="message-form" action="">
        <input type="text" name="message" placeholder="Message" autofocus autocomplete="off"/>
        <button>Send</button>
      </form>
      <button id="send-location"> Send location</button>
    </div>
  </div>

但是刷新结果后代码没有按预期工作 enter image description here

虽然在刷新之前是 enter image description here

【问题讨论】:

  • 我建议您查看JS Cookie,因为它确实可以帮助您更好地管理您的 cookie。它将使无需服务器端代码的持久数据变得更加容易。
  • 无法将 jQuery 对象作为存储值传递。只能在存储中存储字符串。
  • @Schalk.Netgen 建议您阅读存储的工作原理。 Cookie 不是做这种事情的好选择
  • 我确实想保存目标 jQuery('#messages') 的内容
  • 从该元素获取 html,然后 sessionStorage.setItem('ol', jQuery('#messages').html());

标签: javascript jquery html


【解决方案1】:

谢谢@charlietfl 这对我有用

// if an refresh event is fired
window.onbeforeunload = function(event){
  //store the messages into sessionStorage
  sessionStorage.setItem('ol', jQuery('#messages').html());
  return undefined;
};
$(document).ready(function(){
  if (sessionStorage.getItem('ol')) {
  // Restore the contents of the ol (message contents)
    var ol = sessionStorage.getItem('ol');
    jQuery('#messages').html(ol);
  }
});

【讨论】:

    【解决方案2】:

    您需要使用localStorage,因为存储在localStorage 中的数据会一直存在,直到被明确删除。所做的更改会保存下来,可供所有当前和将来访问该网站的用户使用。

    对于sessionStorage,更改仅适用于每个窗口(或 Chrome 和 Firefox 等浏览器中的选项卡)。所做的更改被保存并可用于当前页面,以及将来在同一窗口中访问该站点。窗口关闭后,存储被删除。

    更多详情在此链接https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

    【讨论】:

      猜你喜欢
      • 2014-07-24
      • 2017-03-05
      • 1970-01-01
      • 2021-08-21
      • 2017-11-05
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      相关资源
      最近更新 更多