js使用cookie實現(xiàn)記住用戶名功能示例
本文實例講述了js使用cookie實現(xiàn)記住用戶名功能。分享給大家供大家參考,具體如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>www.dbjr.com.cn cookie記住用戶名</title> <meta name="description" content=""> <meta name="keywords" content=""> </head> <body> <script> //1、cookie的使用:document.cookie = 'key=value';可以同時設置多個 // document.cookie="username=longzhoufeng" // document.cookie="age=03" //2、cookie的過期時間:document.cookie = '名稱=值;expires=' + 字符串格式的時間; // var myDate=new Date() // myDate.setDate(myDate.getDate()+3) // document.cookie="mynameis="+encodeURI("longzhoufeng")+ ";expires="+myDate.toGMTString(); // document.cookie="age=30" // console.log(decodeURI(document.cookie)) // 解碼后輸出結果如下: //mynameis=longzhoufeng; age=30 //3、把上面的封裝成一個函數(shù),其中有三個參數(shù)是在變化的,key值,value值,T時間 function setCookie(key,value,t){ var myDate=new Date() myDate.setDate(myDate.getDate()+t) document.cookie=key+"="+value+ ";expires="+myDate.toGMTString(); } function getCookie(key){ var arr1 = document.cookie.split('; '); for (var i=0; i<arr1.length; i++) { var arr2 = arr1[i].split('='); if ( arr2[0] == key ) { return decodeURI(arr2[1]); } } } function removeCookie(key) { setCookie(key, '', -1); } // setCookie("myName","longzhoufeng",1) // console.log(getCookie("myName")) // console.log(removeCookie("myName")) // alert(typeof myDate) // 必須將時間格式轉換成字符形式 // alert(typeof myDate.toGMTString()); //4、內(nèi)容最好編碼存放,encodeURI //alert( encodeURI('你好') ); //alert( decodeURI('%E4%BD%A0%E5%A5%BD') ) </script> <script> window.onload = function() { var oUsername = document.getElementById('username'); var oLogin = document.getElementById('login'); var oDel = document.getElementById('del'); if ( getCookie('username') ) { oUsername.value = getCookie('username'); } oLogin.onclick = function() { alert('登陸成功'); setCookie('username', oUsername.value, 5); } oDel.onclick = function() { removeCookie('username'); oUsername.value = ''; } } </script> <input type="text" id="username" /> <input type="button" value="登陸" id="login" /> <input type="button" value="刪除" id="del" /> </body> </html>
更多關于JavaScript相關內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)據(jù)結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調(diào)試技巧總結》及《JavaScript數(shù)學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
JS?Angular?服務器端渲染應用設置渲染超時時間???????
這篇文章主要介紹了JS?Angular服務器端渲染應用設置渲染超時時間,???????通過setTimeout模擬一個需要5秒鐘才能完成調(diào)用的API展開詳情,需要的小伙伴可以參考一下2022-06-06JS代碼實現(xiàn)table數(shù)據(jù)分頁效果
這篇文章主要介紹了JS代碼實現(xiàn)table數(shù)據(jù)分頁效果的相關資料,非常不錯,代碼簡答易懂,非常實用,需要的朋友可以參考下2016-05-05setTimeout與setInterval在不同瀏覽器下的差異
setTimeout與setInterval是window對象的兩個非常神奇方法,用于實現(xiàn)定時或延時調(diào)用一個函數(shù)或一段代碼2010-01-01javascript設計模式 – 單例模式原理與應用實例分析
這篇文章主要介紹了javascript設計模式 – 單例模式原理與應用,結合實例形式分析了javascript單例模式原理、定義、應用場景及相關操作注意事項,需要的朋友可以參考下2020-04-04再談querySelector和querySelectorAll的區(qū)別與聯(lián)系
先按W3C的規(guī)范來說這兩個方法應該返回的內(nèi)容吧,大家先看下官方的解釋,然后根據(jù)需要選擇使用2012-04-04