|
<script>
function getCookie(c_name){
if (document.cookie.length>0){ //先查詢cookie是否為空白,為空白就return ""
c_start=document.cookie.indexOf(c_name + "=") //通過String對象的indexOf()來
檢查這個cookie是否存在,不存在就為 -1
if (c_start!=-1){
c_start=c_start + c_name.length+1 //最後這個+1其實就是表示"="號啦,這樣
就擷取到了cookie值的開始位置
c_end=document.cookie.indexOf(";",c_start) //其實我剛看見indexOf()第二個
參數的時候猛然有點暈,後來想起來表示指定的開始索引的位置...這句是為了得到值的結束位置。因為
需要考慮是否是最後一項,所以通過";"號是否存在來判斷
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end)) //通過
substring()得到了值。想瞭解unescape()得Crowdsourced Security Testing道escape()是做什麼的,都是很重要的基礎,想瞭解的
可以搜尋下,在文章結尾處也會進行講解cookie編碼細節
}
}
return ""
}
function setCookie(c_name, value, expiredays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie=c_name+ "=" + escape(value) + "path=/;domain=111cn.net" +
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function sc(days)
{
setCookie('ashow','a',days);
document.getElementById('ad').style.display='none';
}
function gc()
{
if(getCookie('ashow')==1)
{
alert(getCookie('ashow'));
document.getElementById('ad').style.display='none';
}
}
</script>
<div id="ad">fdsafdsafdsafsda</div>
<script>
gc();
</script>
<a href="#" onclick="javascript:sc(1);">設定Cookie值</a>
<a href="#" onclick="javascript:gc();">擷取Cookie值</a>
<a href="#" onclick="javascript:sc(-1);">清除Cookie值</a> |