老师我这输入框怎么是undefined

来源:2-12 自由编程

weixin_精慕门9462467

2021-08-24 11:09:46

// 写入cookie

const set=(name,value,{domain,path,maxAge,secure}={})=>{

    // let name=decodeURIComponent(name)

    // let value=decodeURIComponent(value)

    let cookieText=`${decodeURIComponent(name)}=${decodeURIComponent(value)}`;

    if(typeof maxAge=='number'){

        cookieText+=`; max-age=${maxAge}`;

    }


    if(domain){

        cookieText+=`; domain=${domain}`;

    }

    

    if(path){

        cookieText+=`; path=${path}`;

    }


    if(secure){

        cookieText+=`; secure`;

    }

    document.cookie=cookieText

}


// 通过nam获取cookie的值

const get=(name)=>{

    name=`${encodeURIComponent(name)}`;

    const cookies=document.cookie.split('; ');

    for(const item of cookies){

        const[cookieName,cookieValue]=item.split('=')


        if(cookieName===name){

            return encodeURIComponent(cookieValue)

        }

    }

    return;

}


// 清除cookie

// 根据 name domain path 删除cookie

const remove=(name,{domain,path}={})=>{

    set(name,'',{domain,path,maxAge:-1});

}

export {set,get,remove}


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <style>

        #dl {

            background-colorgreen;

        }

        #sc {

            background-colorred;

        }

    </style>

</head>

<body>

    用户名:<input type="text" placeholder="请输入用户名" id="yhm">

    <button id="dl">登录</button>

    <button id="qc">删除</button>

    <script type="module">

        import {set,get,removefrom './cookie.js'

        let dl =document.getElementById('dl')

        let qc =document.getElementById('qc')

        let yhm=document.getElementById('yhm')

        if(document.cookie!=null){

            yhm.value=get('用户名')

        }

        dl.addEventListener('click',()=>{

            set('用户名',yhm.value,{maxAge:7*24*3600})

            window.location='./index.html'

        },false)

        qc.addEventListener('click',()=>{

            remove('用户名')

            window.location='./index.html'

        },false)

    </script>


</body>

</html>




写回答

1回答

好帮手慕星星

2021-08-24

同学你好,代码问题如下:

1、cookie值不存在,值为空字符串,而不是null

http://img.mukewang.com/climg/6124698f0964b13004150150.jpg

2、get方法中name加密了,但是cookieName没有加密,所以是不相等的。建议都加密,或者都不加密,如下

http://img.mukewang.com/climg/612469d9094806ee07000399.jpg

自己再测试下,祝学习愉快!

0
heixin_精慕门9462467
hp>可以了,谢谢老师

h021-08-24
共2条回复

0 学习 · 15276 问题

查看课程