我们在做页面的时候,如果采用include的时候,点击某一个菜单会调用另一个页面,导致点击的菜单没有显示,所以客户需要的要求是点击完此处时显示的时候还必须显示。
实现此种要求的方式是:
1.把点击的菜单id记入进cookie中
2.在页面加载成功后,读取cookie,完了调用菜单显示的方法
代码如下:
写入和读取cookie
**
* 保存cookie
* @param {Object} name cookie名称
* @param {Object} value 值
* @param {Object} hours 保存时间,单位为小时
*/
function writeCookie(name, value, hours) {
var expire = "";
if (hours != null) {
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + escape(value) + expire;
}
/**
* 读取cookie
* @param {Object} name cookie名称
* @return {TypeName}
*/
function readCookie(name) {
var cookieValue = "";
var search = name + "=";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end))
}
}
return cookieValue;
}
菜单显示方法
/**
* 菜单展示方法
* @param {Object} emid
*/
function DoMenu(emid)
{
//写cookie
writeCookie("hovers", emid, 24);
var obj = document.getElementById(emid);
obj.className = (obj.className.toLowerCase() == "expanded"?"collapsed":"expanded");
if((LastLeftID!="")&&(emid!=LastLeftID)) //关闭上一个Menu
{
document.getElementById(LastLeftID).className = "collapsed";
}
LastLeftID = emid;
}
页面加载成功后显示菜单
$(document).ready(function() { //读取cookie的hovers属性 var temp_c = readCookie("hovers") ; alert(temp_c); if(temp_c && temp_c!="none"){ //让此菜单展开 DoMenu(temp_c); } });
window7cookie保存文件夹C:\Users\用户名\AppData\Local\Microsoft\Windows\Temporary Internet Files
windowXP cookie保存文件夹C:\Documents and Settings\Administrator\Local Settings\Temporary Internet Files
采用jquery cookie插件解决此问题方案
采用插件地址https://github.com/carhartl/jquery-cookie#cookie-options
附件我上传了使用的cookie插件
**
* 保存cookie
* @param {Object} name cookie名称
* @param {Object} value 值
* @param {Object} hours 保存时间,单位为天
*/
function writeCookie(name, value, hours) {
$.cookie(name, value,{expires: 1,path:"/"});
}
/**
* 读取cookie
* @param {Object} name cookie名称
* @return {TypeName}
*/
function readCookie(name) {
var cookieValue = $.cookie(name);
return cookieValue;
}
页面加载成功后显示菜单
$(document).ready(function() {
//读取cookie的hovers属性
var temp_c = readCookie("hovers") ;
//alert("read="+temp_c);
if(temp_c && temp_c!="none"){
//让此菜单展开
DoMenu(temp_c,true);
}
//$.removeCookie("hovers",{ path: '/' });
});
删除cookie
$.removeCookie("hovers",{ path: "/" });
最注意的是path这个参数的使用
理解了path意义就可以解决了!