使用Jquery.Cookie进行记录网页信息以及页面间数据传递

  •   
  • 3889
  • jQuery
  • 0
  • super_dodo
  • 2015/11/16

在一些项目中可能需要记录用户的点击信息,譬如后台的左边菜单栏点击了其中一个呈现展开或者明显加粗选中的形式。以及页面之间的数据传递等都可以使用jquery.cookie来记录。从一定程度上替代了服务端的session或者url上面的传递参数。实现这个方案可能有很多种方式。

此处的需求是,当页面左边菜单栏点击了某个菜单,该菜单选中状态,就保存在jquery.cookie里面,页面刷新或者跳转的时候,当前的菜单还是显示成为选中的状态(你可以判定URL通过PHP).

示例代码如下,此处有三级菜单,略显复杂.


<script src="/js/jquery-1.7.2.js" type="text/javascript"></script>
<script src="/js/jquery.cookie.js" type="text/javascript"></script>


// 页面打开时,根据位置添加样式
if($.cookie('treeLocation')) {
	var arr = $.cookie('treeLocation').split('_');
	if(arr[2]==100){ //如果有三级
	$("#nav").children("li:eq("+arr[0]+")").children("a").removeClass().addClass("tit_cur").end()
		.children("ul").show().children("li:eq("+arr[1]+")").addClass("sub_cur");
	}else{
	$("#nav").children("li:eq("+arr[0]+")").children("a").removeClass().addClass("tit_cur").end()
		.children("ul").show().children("li:eq("+arr[1]+")").children("ul").show().children("li:eq("+arr[2]+")").addClass("sub_cur");
	}
}
		
		
// 导航链接被点击时 记录链接位置到COOKIE
$("#nav li ul li a:not(.noHaver)").click(function() {
	var $threeSelectedIndex = 100 ;
	if(this.id != 'three'){
	   var openIndex =  $(this).parent("li").parent("ul").parent("li").index();
	   var selectedIndex = $(this).parent("li").index();
	}else{
	   var openIndex = $("#nav li a.tit_nav").parent("li").index();
	   var selectedIndex = $(this).parent("li").parent("ul").parent("li").index();
	   $threeSelectedIndex  = $(this).parent("li").index();
	}
	$.cookie('treeLocation', openIndex+'_'+selectedIndex+'_'+$threeSelectedIndex, {'path':'/'});
});

这个是简单点的,主要就是记录页面搜索更多的是否展开

//点击搜索更多的时候
$(".searchMore").click(function(){			//默认隐藏
	var icon = $(this).find(".icon_black");
	if(icon.hasClass("glyphicon-chevron-down")){		//点击打开
		icon.removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
		$(".moreSearch").slideDown();
		$.cookie('moreSearchSet', '1', {'path':'/'});
	}else{										//点击隐藏
		icon.removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
		$(".moreSearch").slideUp();
		$.cookie('moreSearchSet', '0', {'path':'/'});
	}
});


//判断上次页面的查询是否展开的
if($.cookie('moreSearchSet') =='1') {  //如果展开的话
	$(".btn-group span .icon_black").removeClass("icon-chevron-down").addClass("icon-chevron-up");
	$(".moreSearch").css("display","block");
}

不是境况造就人,而是人造就境况。含泪播种的人一定能含笑收获。