JQuery Cookie 无法正常工作

JQuery Cookie not function

我有一个 javascript 函数 showHide(shID) ,这是一个隐藏 div 并在单击 "read more" 后显示内容的函数。这是我的 Fiddle :Fiddle

在这个函数中添加 JQuery Cookie 之后,似乎函数 showHide(shID) 不见了,谁能帮我解决这个问题?谢谢我真的需要帮助。这是我的 Fiddle : Fiddle

我需要这样做smtg:首先点击"readmore",隐藏内容会显示,设置cookie后用户回来访问我的页面隐藏内容仍然显示。

<div id="wrap">
   <a href="#" id="example-show" class="showLink" onclick="showHide('example');">
      <button class="btn-u btn-u-lg btn-block btn-u-dark-orange">
         Read More
      </button>
   </a>
   <div id="example" class="more">
      <iframe width="600" height="315" src="//www.youtube.com/embed/BaPlMMlyM_0" frameborder="0" allowfullscreen></iframe>
      <p>Congratulations! You've found the magic hidden text! Clicking the link below will hide this content again.</p>
   </div>
</div>  

cookies的名字是区分大小写的,你必须读取你之前设置的相同的cookie名称。在你的情况下你设置 jQuery.cookie("showHide-"+shID, 1) 并勾选 jQuery.cookie("showhide-" + "example")。 "showHide-" 和 "showhide-" 不匹配。

编辑:

    if (document.getElementById(shID + '-show').style.display != 'none') {
        // Set cookie when button has been clicked 
        jQuery.cookie("showhide-"+shID, 1);
        // ...
    } else {
        jQuery.cookie("showhide-"+shID, 0);
        // ...
    }

    if (jQuery.cookie("showhide-" + "example") == 1) {
        // Trigger button click if cookie is set 
        $("#example-show").trigger("click");
    }

我稍微更改了脚本逻辑:当 showhide-... 设置为 1 时显示内容。我还向 showHide 函数添加了一个参数:setCookie。当这个是false时,cookie是没有set/changed.

function showHide(setCookie) {
    var shID = $(this).data("showhide")
      , $shEl = $("#" + shID)
      , $showHide = $("#" + shID + '-show')
      ;

    if ($shEl.is(":hidden")) {
        if (setCookie !== false) {
            jQuery.cookie("showhide-" + shID, 1);
        }
        $showHide.hide();
        $shEl.show();
    } else {
        if (setCookie !== false) {
            jQuery.cookie("showhide-" + shID, 0);
        }
        $showHide.show();
        $shEl.hide();
    }
}

jQuery(document).ready(function () {
    $("#example-show").on("click", showHide);
    if (jQuery.cookie("showhide-" + "example") == '1') {
        showHide.call($("#example-show").get(0), false);
    }
});

要添加到期日期,只需将第三个参数传递给 $.cookie 调用:

var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "foo", { expires: date });

(有关详细信息,请参阅 How to expire a cookie in 30 minutes using jQuery?

JSFIDDLE