【问题标题】:Local Storage, Show and hide elements across different html pages本地存储,在不同的 html 页面中显示和隐藏元素
【发布时间】:2014-03-05 21:48:30
【问题描述】:

我的网络应用程序中有两个 html 页面,index.html 和 topic.html。我在topics.html 中有一个按钮,当单击该按钮时,应该使index.html 中隐藏的Div 可见,这样当我导航到index.html 时,Div 必须可见。我知道这可以通过本地存储和 windows.onload 来实现,我怎样才能将它合并到我的代码中,看起来像这样

topics.html

<button id="show">Show</button>

和 JS

$(document).ready(function(){
 $("#show").click(function(){
    $(".me").show();
  });
});

单击#show 按钮时,我希望下面的当前隐藏的 div 像这样可见,这样当我导航到 index.html 时,div 是可见的,当我单击 #hide 按钮时,它应该即使页面重新加载也保持隐藏

Index.html(已编辑)

<div id="rss-feeds" class="me"></div>
<button id="hide">hide</button>

js

$(document).ready(function(){
  $("#hide").click(function(){
   $(".me").hide();
 });
});

我该如何使用本地存储?

【问题讨论】:

    标签: javascript jquery html local-storage show-hide


    【解决方案1】:

    如果你给你的函数命名就很容易:

    $(document).ready(function(){
    
      function showIt(){
        localStorage.shown=1;
        $(".me").show();
      }
    
      if(localStorage.shown==='1'){ showIt(); }
      $("#show").click(showIt);
    
    }); 
    

    这样您就可以从点击事件和从 localStorage 启动期间调用相同的例程。

    【讨论】:

    • 谢谢。当我尝试测试你的代码时,我注意到我需要在必须保持或重新加载的 div 上放置一个#hide 按钮,然后我也使用了隐藏按钮的代码,唯一的问题是它没有持久化当我重新加载页面时,我无法测试代码。请查看我对原始帖子所做的编辑。再次感谢@dandavis
    • 今晚晚些时候我会回复你,但看来你可以在我的答案中调整 css 选择器并将显示更改为隐藏...
    【解决方案2】:

    我使用这个精彩的示例成功地做到了这一点,它对任何可能感兴趣的人都非常有效。

    https://gist.github.com/jakebresnehan/1983968

    <button id="hide-button">Hide</button>
    <button id="show-button">Show</button>
    
    <div id="sign-up-form">
    <p>Sign up form</p>
    </div>
    
    $(document).ready(function($){
    
    if (Modernizr.localstorage) {
    
     $('#hide-button').click(function(e){
    localStorage.setItem('subscribed',true);
      $('#sign-up-form,#hide-button').hide();
      $('#hide-button').hide();
      $('#show-button').show();
    });
    
    $('#show-button').click(function(e){
      localStorage.setItem('subscribed',true);
      localStorage.clear();
      $('#sign-up-form,#hide-button').show();
      $('#show-button').hide();
    });
    
    var is_subscribed = localStorage.getItem('subscribed');
    
    if(is_subscribed){
    console.log('localStorage')
    $('#sign-up-form,#hide-button').hide();
    }
    
    if(!is_subscribed){
    console.log('no localStorage');
    $('#sign-up-form').show();
    $('#show-button').hide();
    }
    
     } 
    
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多