如何使用toggle()在jquery中设置cookie
寻找一个cookie,当用户点击链接时,它将打开div,然后用户可以刷新页面,看到div仍然打开 =======HTML=======如何使用toggle()在jquery中设置cookie,jquery,toggle,session-cookies,setcookie,Jquery,Toggle,Session Cookies,Setcookie,寻找一个cookie,当用户点击链接时,它将打开div,然后用户可以刷新页面,看到div仍然打开 =======HTML======= <a class="show-settings" href="#"></a> 我以前使用过几乎完全相同的用途。它非常轻量级,而且它的文档也很容易理解 所以你可以有这样的东西: // This is assuming the two elements are hidden by default if($.cookie('myCookie'
<a class="show-settings" href="#"></a>
我以前使用过几乎完全相同的用途。它非常轻量级,而且它的文档也很容易理解
所以你可以有这样的东西:
// This is assuming the two elements are hidden by default
if($.cookie('myCookie') === 'on')
$("#s4-ribbonrow, #s4-titlerow").show();
s.click(function () {
$("#s4-ribbonrow, #s4-titlerow").toggle();
// Toggle cookie value
if($.cookie('myCookie') === 'on')
$.cookie('myCookie', 'off');
else
$.cookie('myCookie', 'on');
});
使用jquerycookies和toggle中的回调功能可以实现类似的功能
$(document).ready(function() {
SetView();
$('.show-settings').click(function() {
$('#s4-ribbonrow, #s4-titlerow').toggle(0, function(){$.cookie('show-settings', $("#s4-ribbonrow:visible")});
});
function SetView() {
if ($.cookie('loginScreen') == 'true')
$('#s4-ribbonrow, #s4-titlerow').show();
}
}
你需要这样才能工作
$(function() {
var $s = $("a.show-settings");
//On click to toggle settings
$s.click(function() {
var text = $(this).text();
$("#s4-ribbonrow, #s4-titlerow").toggle();
if(text === 'Show Settings') {
$s.text('Hide Settings');
$.cookie('is-hidden', null); // remove cookie
}else {
$s.text('Show Settings');
$.cookie('is-hidden', 'hidden'); // set cookie
}
return false;
});
if($.cookie('is-hidden')) { // If cookie exists
$("#s4-ribbonrow, #s4-titlerow").hide();
$s.text('Show Settings');
}
});
HTML(假定默认情况下显示设置)
oops,我刚刚意识到默认情况下应该隐藏这些设置。如果需要,我可以修正我的答案。这是最接近的答案,但是,它正在设置cookie。仍在寻找答案。。。有没有不使用插件的方法?不知道你说的“它是在设置cookie”是什么意思?是的,你可以使用香草javascript来设置cookies,而不是插件。它刚刚在这里被破解。。。我没有测试语法是100%。这就是顶部的评论使用cookies和回调的原因。有没有不使用插件的方法?没有。你必须保持状态。您的要求是“它将打开div,然后用户可以刷新页面并看到div仍然打开”。。。这要求您在cookie或会话中保持状态,因为web本质上是无状态的。
$(function() {
var $s = $("a.show-settings");
//On click to toggle settings
$s.click(function() {
var text = $(this).text();
$("#s4-ribbonrow, #s4-titlerow").toggle();
if(text === 'Show Settings') {
$s.text('Hide Settings');
$.cookie('is-hidden', null); // remove cookie
}else {
$s.text('Show Settings');
$.cookie('is-hidden', 'hidden'); // set cookie
}
return false;
});
if($.cookie('is-hidden')) { // If cookie exists
$("#s4-ribbonrow, #s4-titlerow").hide();
$s.text('Show Settings');
}
});
<a class="show-settings" href="#">Hide Settings</a>