jQuery切换Cookie支持

我正在尝试将jQuery Cookie插件实现到我的幻灯片切换脚本中,但到目前为止还没有成功。 这是我的代码(没有任何cookie实现):

jQuery的:

$(document).ready(function() { $('a.toggle').click(function() { var id = $(this).attr('name'); $('#module' + id).slideToggle('fast'); $('a.toggle[name='+id+']').toggle(); return false; }); }); 

HTML:

 - Hide  

Hello World

任何人都知道在现有代码中实现jQuery Cookie插件是否容易,以便记住打开/关闭状态?

谢谢。

jQuery cookie插件非常易于使用。 基本上你需要做的就是在使用切换时通过cookie设置一个标志。

要在站点范围内设置值,像这样的简单语句有效:

 $.cookie("currentToggle", "on", {path: "/"}); 

然后在需要时获取值,使用:

 var currentState = $.cookie("currentToggle"); 

我不确定你打算如何使用切换,但是举个例子,你需要跟踪多个页面的状态。 当切换触发时,您可以轻松设置cookie,跟踪其所处的状态(开/关等)。 在其他页面加载期间,公共脚本可以检查cookie并根据标志设置切换。 这将使网站的外观“记住”跨页面的先前状态。

无论如何只是一个样本使用。 希望这可以帮助。

jQuery Cookie插件: http : //www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

编辑以提供实施示例:

这是一个有效的示例实现。 需要引用jQuery和jQuery cookie插件,以及一个css定义。 当在每个页面上定义所有脚本和CSS时,跨多个页面工作。

使用Javascript:

 $(document).ready(function() { var button = $('#hideButton'); //check the cookie when the page loads if ($.cookie('currentToggle') === 'hidden') { togglePanel(button, false); } else { togglePanel(button, true); } //handle the clicking of the show/hide toggle button button.click(function() { //toggle the panel as required, base on current state if (button.text() === "+Show") { togglePanel($(this), true); } else { togglePanel($(this), false); } }); }); function togglePanel(button, show) { var panel = $('#panel'); if (show) { panel.removeClass('hidden'); button.text('-Hide'); $.cookie('currentToggle', '', { path: '/' }); } else { panel.addClass('hidden'); button.text('+Show'); $.cookie('currentToggle', 'hidden', { path: '/' }); } } 

CSS:

 .hidden { display: none; } 

标记:

 -Hide 

Hello World

可能有更多有效的方法来实现它,但为了快速certificate概念,上述方法效果很好。