【问题标题】:Saving JQuery Toggle State with Cookie使用 Cookie 保存 JQuery 切换状态
【发布时间】:2014-05-22 22:39:32
【问题描述】:

我有一个 iFrame,在单击按钮时可以切换为可见或隐藏。我正在使用 JQuery .toggle 函数来执行此操作。目前该区域的 div 默认通过 CSS 隐藏:style="display:none"

一个新的要求出现了,要求保存用户最近的显示或隐藏(选择的切换状态)以供下一个页面加载,所以如果他们上次在主页时选择显示 iFrame,他们下次访问时,默认情况下将可见。我想用 cookie 设置最后选择的切换状态,但我无法让它工作。以下是我的代码:

<meta charset="utf-8">
<title>drop demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<style>
  #toggle {
    width: 100px;
    height: 100px;
    background: #ccc;
  }
  .button {
    padding-top: 10px;
    padding-right: 20px;
  }
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<button type="button" id="button"
title="Personalized Sales Dashboard">Show/Hide</button>
<div id="toggle" style="display:none" frameborder="2">
<iframe src="https://sample.com"="" id="myfr" scrolling="no" frameborder="0"
 height="800px" width="100%">Your Browser Do not Support Iframe</iframe>
</div>
<script>
  $("#button").click(function () {
    $("#toggle").toggle("blind");
  });
  $(function () {
    $("#button").tooltip();
  });
</script>

【问题讨论】:

    标签: javascript jquery html css cookies


    【解决方案1】:

    在你的按钮上设置一个cookie点击div是否可见:

    document.cookie = "toggleState=" + $("#toggle").is(':visible');
    

    并在页面加载时检索它,相应地显示或隐藏内容:

    var toggleState = document.cookie.replace(/(?:(?:^|.*;\s*)toggleState\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    
    if (toggleState == 'true') {
        $("#toggle").show();
    }
    else {
        $("#toggle").hide();
    }
    

    https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-16
      • 2019-02-11
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多