简体   繁体   English

javascript-为什么我不能使用存储变量而不是本地存储?

[英]javascript- why can't i use stored variables instead of local storage?

So I tried to replace this code below that uses localStorage 所以我尝试在下面使用localStorage替换此代码

var myButton = document.querySelector('button');
var myHeading = document.querySelector('h1');

function setUserName() {
  var myName = prompt('Please enter your name.');
  localStorage.setItem('name', myName);
  myHeading.textContent = 'Mozilla is cool, ' + myName;
}
if(!localStorage.getItem('name')) {
  setUserName();
} else {
  var storedName = localStorage.getItem('name');
  myHeading.textContent = 'Mozilla is cool, ' + storedName;
}
myButton.onclick = function() {
  setUserName();
}

with this code that retrieves from a stored variable. 使用此代码从存储的变量中检索。

var myButton = document.querySelector('button');
var myHeading = document.querySelector('h1');

var myName;
function setUserName() {
  myName = prompt('Please enter your name.');
  //localStorage.setItem('name', myName);
  myHeading.textContent = 'Mozilla is cool, ' + myName;
}
if(!myName) {
  setUserName();
} else {
  //var storedName = localStorage.getItem('name');
  myHeading.textContent = 'Mozilla is cool, ' + myName;
}
myButton.onclick = function() {
  setUserName();
}

why does it not work accordingly? 为什么它不能相应地工作?

When you refresh the page any variables are cleared. 刷新页面时,所有变量都将被清除。 As such the if(!myName) returns true and the user is prompted again. 这样, if(!myName)返回true,并再次提示用户。 LocalStorage allows you to save your variables as key/value pairs between page refreshes in the browser. LocalStorage允许您将变量保存为浏览器中页面刷新之间的键/值对。

Also, check out this answer on sessionStorage vs localStorage: HTML5 Local storage vs. Session storage 另外,在sessionStorage vs localStorage上查看以下答案: HTML5 Local storage vs. Session storage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM