js 存cookie 和 取cookie一個小小小的小栗子
阿新 • • 發佈:2020-12-12
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <div> <input type="text" class="setCookieName" placeholder="請輸入cookie名"> <input type="text" class="setCookieVal" placeholder="請輸入cookie值"> <button id="save">儲存</button> </div> <div> <input type="text" class="seeCookieVal" placeholder="請輸入cookie名檢視cookie值"> <button id="see">檢視</button> <div class="qresults"></div> </div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <script> //動態設定 $("#save").click(function() { setCookie($(".setCookieName").val(),$(".setCookieVal").val()); $(".setCookieName").val(""); $(".setCookieVal").val(""); }) // 動態檢視 $("#see").click(function() { var txt = getCookie($(".seeCookieVal").val()); $(".qresults").html(txt) })function setCookie(name, value) { var Days = 30; //有效期為30天 //取出當前日期,加上30天,得出有效截止日期 var exp = new Date(); exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expries =" + exp.toGMTString(); } function getCookie(name) {var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; } </script> </body> </html>
記得下班打卡,麼麼麼麼麼噠