怎樣操作純JS操作Cookie

來源:互聯網
上載者:User
這次給大家帶來怎樣操作純JS操作Cookie,操作純JS操作Cookie的注意事項有哪些,下面就是實戰案例,一起來看一下。

cookie 是儲存於訪問者的電腦中的變數。每當同一台電腦通過瀏覽器請求某個頁面時,就會發送這個 cookie。你可以使用 JavaScript 來建立和取回 cookie 的值。

添加Cookie

描述:

建立一條Cookie,交由瀏覽器管理!

參數說明:

name - 索引值對的鍵,唯一標記一個值

value - 索引值對的值,cookie儲存的內容

expdays - cookie到期時間(有效時間)

function setCookie ( name, value, expdays ){    var expdate = new Date();    //設定Cookie到期日期    expdate.setDate(expdate.getDate() + expdays) ;    //添加Cookie    document.cookie = name + "=" + escape(value) + ";expires=" + expdate.toUTCString();}

擷取Cookie

描述:

根據參數name,擷取cookie裡面對應的value值

function getCookie ( name ){    //擷取name在Cookie中起止位置    var start = document.cookie.indexOf(name+"=") ;    if ( start != -1 )    {        start = start + name.length + 1 ;        //擷取value的終止位置        var end = document.cookie.indexOf(";", start) ;        if ( end == -1 )            end = document.cookie.length ;        //截獲cookie的value值,並返回        return unescape(document.cookie.substring(start,end)) ;    }    return "" ;}

刪除Cookie

描述:

根據name,刪除一條cookie(設定立即到期)

function delCookie ( name ){    setCookie ( name, "", -1 ) ;}

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

相關閱讀:

瀏覽器不相容我寫的代碼怎麼辦

JS常用的數組方法總結

Vue.js的圖文詳解

nodej中的xml2js需要如何使用

使用Pixi.js的總結

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.