A simple script显示调色板。我使用 jQuery.ready 来初始化它。当我单击颜色时,脚本只会更改单击框的类,以便其上出现一个复选框。它还将颜色值放入隐藏字段中。
现在,我单击导航栏转到另一个页面,然后单击后退按钮。隐藏字段中的值仍然在这里。但颜色框不再被选中(firebug 确认该类不再存在)。
如何确保返回页面时jquery动态设置的类仍然在这里?
(我在最新的 FF 和 IE 中尝试过这个)
最佳答案
您不能依赖浏览器来维护您的网站状态。当您使用后退按钮并且隐藏字段值仍然存在时,请考虑额外,您可能不会在其他浏览器中获得相同的行为。
这意味着您必须自己保存和维护网站状态。如果您使用 ajax 来导航您的网站,您可以使用对象轻松维护状态,但由于情况并非如此,解决方案可能是使用 cookie。
编辑:HTML5 Web Storage也可以是替代解决方案,同样的逻辑适用。
以下代码由 W3Schools 编写,摘自 http://www.w3schools.com/js/js_cookies.asp
设置 cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
获取cookie值
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
因此,当用户选择颜色时,您基本上会设置一个 cookie(使用 setCookie()
),并且每次加载页面时,您都会检查 cookie 值(使用 getCookie( )
) 并相应地填充页面。
示例
//User has chosen a color, save that in a cookie for 1 day
setCookie("selectedColor", "green", 1);
//Page is loaded, check for cookie value...
$(document).ready(function()
{
//Get cookie value
var selectedColor = getCookie("selectedColor");
if(selectedColor != "")
{
//A color has been previously selected, add the CSS class accordingly
$("#"+selectedColor).addClass("selected");
}
});
编辑:仅在来自另一个站点时保持状态(不仅仅是点击后退按钮)。重新加载会清除所有内容。
假设用户在 page1.html
中设置颜色,然后转到 page2.html
,然后返回 page1.html
.
在page1.html
中将选定的颜色值保存在cookie中,与之前相同。
//User has chosen a color, save that in a cookie for 1 day
setCookie("selectedColor", "green", 1);
但是现在,当 page1.html
加载时,如果某个 cookie(如下所述)设置为 true
,则仅使用先前可能选择的值填充页面。
//page1 is loaded
$(document).ready(function()
{
//Only populate page if "populate" cookie is set to true
if( getCookie("populate") != "true" )
{ return; //Stop }
//Get cookie value
var selectedColor = getCookie("selectedColor");
if(selectedColor != "")
{
//A color has been previously selected, add the CSS class accordingly
$("#"+selectedColor).addClass("selected");
//Set "populate" cookie to false
setCookie("populate", "false", 1);
}
});
现在,在 page2.html
中执行以下操作:
//page2 is loaded
$(document).ready(function()
{
//Set "populate" cookie to true
setCookie("populate", "true", 1);
}
这样做的目的是让您能够在访问者到达 page1.html
时知道他们是否来自其他页面。请记住,如果用户这样做...
page1.html -> page2.html -> google.com -> page1.html
..这些值仍然存在。重新加载 page1.html
会清除所有内容。不幸的是,我无法为您提供 HTML5 Web Storage 示例,因为我从未使用过它,但应用相同的逻辑将会给您类似的结果。
希望这有帮助。
关于jquery - jquery 设置的 css 样式在后退按钮后丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9948594/