亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問JS 該怎么保存Cookie~~?

請問JS 該怎么保存Cookie~~?

鴻蒙傳說 2019-07-03 07:03:52
JS 怎么保存Cookie~~
查看完整描述

4 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

js保存COOKIE,直接給document加上cookie就可以了,但是一般如果單個的加會很麻煩所以一般會直接寫好一個函數,可以直接操作cookie,這樣就很方便了

setCookie這個是寫入cookie,第一個是名稱,第二個是cookie值,第三個是過期時間

getCookie這個是查找cookie;

removeCookie這是你需要刪除的cookie;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

function setCookie(name, value, iDay) 

{

    var oDate=new Date();

     

    oDate.setDate(oDate.getDate()+iDay);

     

    document.cookie=name+'='+encodeURIComponent(value)+';expires='+oDate;

}

 

function getCookie(name)

{

    var arr=document.cookie.split('; ');

    var i=0;

    for(i=0;i<arr.length;i++)

    {

        //arr2->['username', 'abc']

        var arr2=arr[i].split('=');

         

        if(arr2[0]==name)

        {  

            var getC = decodeURIComponent(arr2[1]);

            return getC;

        }

    }

     

    return '';

}

 

function removeCookie(name)

{

    setCookie(name, '1', -1);

}


查看完整回答
反對 回復 2019-07-07
?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

<!DOCTYPE HTML>

<html lang="en-US">

<head>

<meta charset="UTF-8">

<meta name="keywords" content="白菜編輯部">

<title>白菜編輯部</title>

<style type="text/css">

</style>

<script type="text/javascript">

    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;

    }

    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;

    }

      

    writeCookie ("myCookie", "my name", 24);

    alert (readCookie ("myCookie"));

</script>

</head>

<body>

</body>

</html>

 


查看完整回答
反對 回復 2019-07-07
  • 4 回答
  • 0 關注
  • 1566 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號