【问题标题】:How to use the local storage only for the current page. in Jquery如何仅对当前页面使用本地存储。在jQuery中
【发布时间】:2014-09-25 21:35:19
【问题描述】:

当导航离开当前页面时,是否可以以某种方式清除 localStorage 值。

我正在尝试将页面的 scrollTop 值保存在 localStorage 变量中,并在页面刷新时使用它滚动到该点。

但是如果我转到不同的页面,我希望将 localStorage 值再次设置为空。

有什么简单的方法可以解决

更新

Blaze 提供的答案添加到我的脚本及其生成错误

脚本

$(document).on('vclick','#outerPage',function(e){
  // alert('yo i am clickable now'); 
    var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
  // localStorage.setItem("scrollPosition", relY);
   //storePosition.topCoordinate = relY; 
  //alert(relY);
    obj = JSON.parse( localStorage.getItem('scrolls') );
    obj[location.pathname] = relY;
    localStorage.setItem('scrolls', JSON.stringify(obj) ); 
    console.log(localStorage.getItem("scrolls"));
});

错误

Uncaught TypeError: Cannot set property '/url.html' of null 

感谢和问候

【问题讨论】:

    标签: jquery html jquery-mobile local-storage


    【解决方案1】:

    是的

    只需使用 jquery 的卸载功能jquery/unload

    在卸载功能上,只需清除本地存储

    localStorage.clear();
    

    【讨论】:

    • 我也试过了,但是没有调用函数:(。我的意思是我使用了 unload()
    • @Blazemonger 但我没有完全使用 JQuery 移动版的布局,它只是带有一些 Jquery css 的普通网站。所以当我点击链接时,它会打开不同的网址,据说你的想法应该有效。
    • 也许就在你打开url之前,你只是清除了localstorage。
    猜你喜欢
    • 2015-02-10
    • 2015-08-01
    • 2021-06-28
    • 2012-11-21
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多