以前写的代码,写得比较简单。这里贴一下,我觉得可以作为演示JavaScript操作cookie用:)
效果看这里,完整代码(代码中的CookieManager拷贝自O'Reilly的《JavaScript & DHTML Cookbook》,Utility.each函数拷贝自jQuery中的each)在这里。
下面是关键的代码部分:
var PlayList = {
cookieName:'PlayListIds',
//保存要播放的视频id列表
ids:[],
//过期时间 单位秒
expires:30,
//读取cookie保存的播放列表信息 播放id保存格式为1232.1221.213.123 以.间隔
read:function(){
var cookieString = CookieManager.get(this.cookieName);
return cookieString != '' ? cookieString.split('.') : [];
},
//获取视频id在数组中的索引
indexOf:function(id){
for(var i =0 ; i < this.ids.length; i++)
if(this.ids[i] == id.toString())
return i;
return -1;
},
//更新cookie信息
update:function(){
CookieManager.set(
this.cookieName,
this.ids.join('.'),
CookieManager.getExpiresDate(0,0,this.expires),
'/',
'.abc.com'
);
},
//增加视频
add:function(id){
if(typeof id != "number" || this.indexOf(id) != -1) return;
this.ids.push(id.toString());
this.update();
},
//移除视频
remove:function(id){
var index = -1;
if(typeof id != "number" || (index = this.indexOf(id)) == -1) return;
this.ids.splice(index,1);
this.update();
},
//清空列表
clear:function(){
CookieManager.clear();
var pItem = null,pItemSel = null;
for(var i = 0; i < this.ids.length; i++){
if( (pItemSel = $('playlist-item-sel-'+this.ids[i])) != null
&& (pItem = $('playlist-item-'+this.ids[i])) != null )
{
pItemSel.className = "unselected";
pItemSel.title = "添加到点播单";
pItem.getElementsByTagName("img")[0].style.border = "5px solid white";
}
}
},
//渲染
renderSelected:function(){
var pItem = null,pItemSel = null;
for(var i = 0; i < this.ids.length; i++){
if( (pItemSel = $('playlist-item-sel-'+this.ids[i])) != null
&& (pItem = $('playlist-item-'+this.ids[i])) != null )
{
pItemSel.className = "selected";
pItemSel.title = "从点播单移除";
pItem.getElementsByTagName("img")[0].style.border = "5px solid yellow";
}
}
},
//处理点击
toggle:function(el){
if(el.className == 'unselected'){
el.className = 'selected';
el.title = "从点播单移除";
el.parentNode.getElementsByTagName("img")[0].style.border = "5px solid yellow";
this.add(parseInt(el.getAttribute('sid')));
} else {
el.className = 'unselected';
el.title = "添加到点播单";
el.parentNode.getElementsByTagName("img")[0].style.border = "5px solid white";
this.remove(parseInt(el.getAttribute('sid')));
}
},
//绑定事件
attachEvent:function(){
var _ = this;
var els = Utility.getElementsByClassName("playlist","a","unselected");
els = els.concat(Utility.getElementsByClassName("playlist","a","selected"));
Utility.each(els,function(i,el){
Utility.bind(el,'click',_.toggle,_,el)
})
},
//初始化
init:function(){
this.ids = this.read();
this.renderSelected();
this.attachEvent();
}
}