如何在JavaScript中创建Cookie?

生成cookie的JavaScript代码如下:,,“javascript,function setCookie(name, value, days) {, var expires = "";, if (days) {, var date = new Date();, date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));, expires = "; expires=" + date.toUTCString();, }, document.cookie = name + "=" + (value || "") + expires + "; path=/";,},,// 使用示例:设置一个名为"myCookie"的cookie,值为"Hello World",有效期为7天,setCookie("myCookie", "Hello World", 7);,

生成Cookie的JavaScript代码

在JavaScript中,可以使用document.cookie属性来创建、读取和删除cookie,以下是一个简单的示例,演示如何创建一个名为username,值为JohnDoe的cookie,并设置其过期时间为1天(86400秒):

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
// 使用函数设置cookie
setCookie("username", "JohnDoe", 1);

源码解析

1、函数定义setCookie函数接受三个参数:name(cookie的名称),value(cookie的值)和days(cookie的过期天数)。

2、过期时间计算:如果提供了days参数,则计算出cookie的过期日期,这是通过获取当前日期,然后添加指定的天数来实现的。

3、设置cookie:使用document.cookie属性将cookie添加到浏览器中,这里设置了cookie的路径为根路径(path=/),这意味着该cookie在整个网站上都可用。

相关问题与解答

如何在JavaScript中创建Cookie?

问题1:如何在JavaScript中读取cookie?

答案:要读取cookie,你可以使用以下函数:

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
// 使用函数读取cookie
var username = getCookie("username");
console.log(username); // 输出: JohnDoe

问题2:如何在JavaScript中删除cookie?

答案:要删除cookie,你可以将其过期日期设置为过去的某个时间点,以下函数会删除名为username的cookie:

function deleteCookie(name) {
    document.cookie = name + '=; MaxAge=99999999;';
}
// 使用函数删除cookie
deleteCookie("username");

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1085114.html

本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。

(0)
未希新媒体运营
上一篇 2024-09-25 08:03
下一篇 2024-09-25 08:05

相关推荐

  • 如何实现简单实用的JavaScript tabel切换?

    JavaScript tab切换可以通过以下几种简单实用的方法实现:使用CSS类切换显示/隐藏内容,使用JavaScript改变元素的style.display属性,或者通过修改HTML的innerHTML来动态加载内容。

    2024-12-23
    06
  • 在线表格如何创建与编辑?

    在线表格的创建可以通过多种方式实现,包括使用在线文档编辑工具、在线表格工具以及云存储服务。选择合适的平台后,可以按照相应的步骤进行创建和编辑。

    2024-12-23
    06
  • 你想知道如何实现一个JavaScript滚动条插件吗?

    “javascript,class ScrollBar {, constructor(container) {, this.container = container;, this.init();, },, init() {, const scrollbar = document.createElement(‘div’);, scrollbar.style.width = ’10px’;, scrollbar.style.background = ‘#ddd’;, scrollbar.style.position = ‘absolute’;, scrollbar.style.right = ‘0’;, scrollbar.style.top = ‘0’;, scrollbar.style.bottom = ‘0’;, this.scrollbar = scrollbar;, this.container.appendChild(this.scrollbar);,, this.handle = document.createElement(‘div’);, this.handle.style.width = ’50px’;, this.handle.style.background = ‘#888’;, this.handle.style.position = ‘absolute’;, this.handle.style.cursor = ‘grab’;, this.handle.style.userSelect = ‘none’;, this.handle.style.height = ’20px’;, this.handle.style.borderRadius = ’10px’;, this.handle.style.marginTop = ‘-10px’;, this.handle.addEventListener(‘mousedown’, this.startDrag.bind(this));, this.scrollbar.appendChild(this.handle);,, this.container.addEventListener(‘scroll’, () =˃ {, const maxScrollTop = this.container.scrollHeight this.container.clientHeight;, const scrollRatio = this.container.scrollTop / maxScrollTop;, this.handle.style.top = ${scrollRatio * (this.container.clientHeight this.handle.offsetHeight)}px;, });,, this.updateHandleSize();, },, startDrag(event) {, event.preventDefault();, const startY = event.clientY;, const startTop = parseInt(this.handle.style.top, 10);, const containerRect = this.container.getBoundingClientRect();, const maxScrollTop = this.container.scrollHeight this.container.clientHeight;, const handleHeight = this.handle.offsetHeight;,, const onMouseMove = (moveEvent) =˃ {, const deltaY = moveEvent.clientY startY;, const newTop = Math.min(Math.max(startTop + deltaY, 0), containerRect.height handleHeight);, const scrollRatio = newTop / (containerRect.height handleHeight);, this.container.scrollTop = scrollRatio * maxScrollTop;, };,, const onMouseUp = () =˃ {, document.removeEventListener(‘mousemove’, onMouseMove);, document.removeEventListener(‘mouseup’, onMouseUp);, };,, document.addEventListener(‘mousemove’, onMouseMove);, document.addEventListener(‘mouseup’, onMouseUp);, },, updateHandleSize() {, const containerHeight = this.container.clientHeight;, const contentHeight = this.container.scrollHeight;, const handleHeight = Math.max((contentHeight / containerHeight) * containerHeight, 30); // Minimum handle height of 30px, this.handle.style.height = ${handleHeight}px;, },},,// 使用示例,const myContainer = document.getElementById(‘myContainer’);,new ScrollBar(myContainer);,“

    2024-12-23
    07
  • 你了解哪些常用的JavaScript静态类?

    当然,这里有一个常用的JavaScript静态类示例:,,“javascript,class MathUtils {, static add(a, b) {, return a + b;, },, static subtract(a, b) {, return a b;, },, static multiply(a, b) {, return a * b;, },, static divide(a, b) {, if (b === 0) throw new Error(“Division by zero”);, return a / b;, },},“

    2024-12-23
    012

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

产品购买 QQ咨询 微信咨询 SEO优化
分享本页
返回顶部
云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购 >>点击进入