如何使用 localStorage 记住用户名

How do I use localStorage to remember a user’s name

已检查此代码是否存在错误,并检测到 none。但是,当它运行时,它会提示 null。

对于Sololearners我的代码位:https://code.sololearn.com/WOv1cF0EewdB/?ref=app

这是为什么?*

window.onload = function() {

let reload_interval= setInterval(rel, 120000);

if (localStorage.getItem('visit') !== true) { 


    let username = prompt('Enter your name:');

    if (confirm('Do you want to be known as ' + username + ' from now on?')) {

        localStorage.setItem('name', username);

    } else {

        username = prompt('OK then, enter your name:');

        if (confirm('Do you want to be known as ' + username + 'from now on?')) {

            localStorage.setItem('name', username);

        }

    }

    localStorage.setItem('visit', true);

}

if (localStorage.getItem('visit') === true) {

    document.getElementById('p').innerHTML = localStorage.getItem('name');
    
     alert('Hello, ' + localStorage.getItem('name'));

}


};

function clearLocalStorage() {
if (confirm('Do you want to clear current username data?')) {
  localStorage.clear();
    alert('Cleared');
}
}

*jQuery 答案还可以

您没有收到问候警报是因为您正在使用 === true!== true 检查 getItem 的 return 值。

setItem 会将您的值转换为 string,因此 localStorage.getItem('visit') === true 永远不会 为真

如果你想检查用户是否访问过该页面,你应该使用=== "true"(已访问)和!== "true"(未访问)因为它returns string.