Javascript 用户数据不';无法在本地存储中更新

Javascript 用户数据不';无法在本地存储中更新,javascript,Javascript,我的HTML: <!doctype html> <html> <title>Edit Profile</title> <head> <link rel="stylesheet" type="text/css" href="EditProfileCSS.css"/> <script type="text/javascript" src="EditProfileJS.js"/></script> <

我的HTML:

<!doctype html>
<html>
<title>Edit Profile</title>
<head>
<link rel="stylesheet" type="text/css" href="EditProfileCSS.css"/>
<script type="text/javascript" src="EditProfileJS.js"/></script>
<script type="text/javascript" src="CommonScript.js"/></script>
<link rel="stylesheet" type="text/css" href="CommonStyle.css"/>

<script>
var currentUser=userList;

document.addEventListener("DOMContentLoaded",loadUserData);

function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);

document.getElementById('username').value = currentUser.username;
document.getElementById('name').value = currentUser.name;
document.getElementById('password').value = currentUser.password;
document.getElementById('email').value = currentUser.email; 




console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
    }
}


function saveChanges(username , name, password, email){
currentUser = JSON.stringify({username:username,name:name,password:password,email:email});
localStorage.setItem("currentUser",currentUser);
  return currentUser;
}

document.getElementById('saveChanges').addEventListener("click",function(){
saveChanges(
document.getElementById('username').value,
document.getElementById('name').value,
document.getElementById('password').value,
document.getElementById('email').value
);
 currentUser = loadUserData();
document.getElementById('username').value = currentUser.username;
document.getElementById('name').value = currentUser.name;
document.getElementById('password').value = currentUser.password;
document.getElementById('email').value = currentUser.email;
});


</script>

</head>
<body onload="loadUserData()">
<!--edit profile-->
<form action="EditProfile.html" method="post" id="userData" onload="loadUserData()">
<h2 id="title">Edit Profile</h2>
<fieldset id="fieldset">
<div class="content">
<p>
<label for="profilepic">Change Profile Picture<!--img    src="images/profile_pic.png"/--></label>

<input type="file" id="profilepic" name="profilepic" accept="image/*"   onchange="uploadPicture(event)" />
<img id="output"/>
</p>
<p>
<label for="newusername">Username:</label>
<input type="text" name="username"  id="username"  required="required"/>
</p>
<p>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required="required"/>
</p>
<p>
<label for="cpassword">Current Password:</label>
<input type="password" id="password" name="password"  required="required"/> 
</p>

<p>
<label for="password1">New Password:</label>
<input type="password" id="password1" name="password1" />
</p>
<p>
<label for="password2">Confirm Password:</label>
<input type="password" id="password2" name="password2"  />
</p>

<p>
<label for="email">Change Email:</label>
<input type="email" name="email" id="email" required="required"/>

</p>


</form>

 <input type="submit" id="saveChanges" value="Save Changes" onclick="Validate();"  onclick="VerifyPassword();"/>
</div>
</fieldset>
</body>
</html>

在当地

上一个问题的链接:


编辑:我改变了提问的方式,因为另一位用户反馈我的提问方式不对。希望您对此感到满意,我不是故意的

我推荐以下方法:

// making an object comprised of functions,
// in order to group related functions together:
var userData = {
  'get': function() {
    // here we retrieve the stored data (stored with
    // the key of 'data'):
    var data = window.localStorage.getItem('data');

    // typically retrieving an item that doesn't exist
    // will store null as the value of the variable to
    // which that item should be assigned, but here we
    // check for undefined as well (just to be sure):
    if (null === data || 'undefined' === typeof data) {
      // we exit the function here, since there's nothing
      // to be done with an empty/null data variable:
      return false;
    } else {

      // otherwise, if we have data, then we pass that
      // JSON string to JSON.parse() to turn it into
      // an iterable object:
      data = JSON.parse(data);
    }

    // we should have data at this point (since if we
    // we didn't we should have exited the function),
    // but I really like to be sure:
    if (data) {

      // retrieving an Array of keys from the data
      // object, and iterating over that array with
      // Array.prototype.forEach():
      Object.keys(data).forEach(function(key) {
        // 'key' : the first argument is a reference
        //         to the current array-element of
        //         the array of keys over which
        //         we're iterating.

        // we retrieve the element from the document with
        // the id matching the key, and assign the
        // defaultValue of that element to the stored
        // value from the data Object:
        document.getElementById(key).defaultValue = data[key];
      })
    }
  },
  'set': function(e) {
    // because we're binding this function to an element
    // using addEventListener the even is passed through
    // automatically, therefore we call event.preventDefault()
    // to prevent the default action of the element,
    // for a button on a form element that default action
    // may cause a page reload, which we don't want:
    e.preventDefault();

    // finding the relevant form fields to be stored:
    var fields = document.querySelectorAll('#username, #name, #email, #password'),
      // converting the HTMLCollection returned from
      // document.querySelectorAll() into an Array,
      // using Array.from() if it's available or,
      // otherwise, an older approach which calls
      // Array.prototype.slice() to convert the
      // HTMLCollection into an Array:
      fieldArray = Array.from ? Array.from(fields) : Array.prototype.slice.call(fields, 0),

      // initialising an Object to store the
      // properties temporarily:
      store = {};

    // if every element in the array of elements has
    // a truthy trimmed value, or defaultValue, with
    // a length > 0 we go ahead:
    if (fieldArray.every(function(el) {
        return (el.value || el.defaultValue).trim().length;
      })) {
      // iterating over the fieldArray:
      fieldArray.forEach(function(input) {

        // if the value of the <input> element,
        // once trimmed (removing leading and
        // trailing white-space) has a length
        // greater than 0 (0 is falsey):
        if (input.value.trim().length) {

          // we set the key of of the value to
          // store to the id of the current
          // <input> element, and store the
          // value in the object with that key:
          store[input.id] = input.value;

          // we also remove the 'error' class-
          // name if the element has that class:
          input.classList.remove('error');
        } else {

          // otherwise, we set the value to that
          // held in the defaultValue:
          input.value = input.defaultValue;

          // add the 'error' class-name:
          input.classList.add('error');

          // and store the defaultValue in the
          // Object, since the Object itself
          // will overwrite the stored Object
          // so we need to explicitly re-store
          // the old value to prevent empty
          // entries:
          store[input.id] = input.defaultValue;
        }
      });

      // here we store the data in localStorage with the
      // key of 'data' and the value as the JSON string
      // formed by the 'store' Object:
      window.localStorage.setItem('data', JSON.stringify(store));

      // otherwise, given that we have no pre-existing data to
      // store, we don't store any supplied data and we add an
      // 'error' class-name to each field that doesn't yet
      // hold a value (note that I'm not testing for validity
      // of values, simply existence):
    } else {

      // using Array.prototype.filter() to filter the Array
      // of elements to keep only those whose value, or
      // defaultValue, is 0 once it's trimmed:
      fieldArray.filter(function(el) {
        // removing the 'error' class-name from
        // each element:
        el.classList.remove('error');
        return (el.value || el.defaultValue).trim().length === 0;
      }).forEach(function(el) {
        // adding the 'error' class-name to each of the
        // elements that are retained from the filter:
        el.classList.add('error');
      });
    }

    // purely for debuggging, so that you can see what's
    // being saved; remove this (obviously) once you're
    // happy:
    document.getElementById('result').textContent = window.localStorage.getItem('data');
  },

  // the clear function, to allow the user to
  // empty/remove their stored data:
  'clear': function(e) {
    // again we use event.preventDefault() to
    // prevent the default action:
    e.preventDefault();

    // and then we clear the localStorage:
    window.localStorage.clear();

    // we could, instead, simply use:
    // window.localStorage.removeItem('data');
    // to do the same thing, but this will only
    // remove the 'data' item, and leave anything
    // and everything else; which seems like a
    // bad UI based on user-expectation.

    // clearing the visible data from the <form>
    // with which this <button> element was associated:
    this.form.reset();
  }
}

// binding the named functions (note the lack of parentheses) to
// the named events of the elements:
document.querySelector('#save').addEventListener('click', userData.set);
document.querySelector('#clear').addEventListener('click', userData.clear);

// calling the get() function on page-load:
userData.get();
//制作由函数组成的对象,
//为了将相关功能组合在一起:
var userData={
“get”:函数(){
//这里我们检索存储的数据(使用
//“数据”的键):
var data=window.localStorage.getItem('data');
//通常检索不存在的项
//将null存储为变量的值
//应该分配哪个项目,但我们在这里
//检查是否存在未定义(只是为了确保):
如果(null==数据| |“未定义”==数据类型){
//我们在这里退出函数,因为这里什么都没有
//要使用空/空数据变量完成:
返回false;
}否则{
//否则,如果我们有数据,我们就传递它
//将JSON字符串转换为JSON.parse(),以将其转换为
//可复制对象:
data=JSON.parse(数据);
}
//我们现在应该有数据(因为如果我们
//我们没有,我们应该退出函数),
//但我真的很想确定:
如果(数据){
//从数据中检索密钥数组
//对象,并使用
//Array.prototype.forEach():
Object.keys(数据).forEach(函数(键){
//“key”:第一个参数是引用
//到的当前数组元素
//其上的键的数组
//我们正在迭代。
//我们使用
//与密钥匹配的id,并分配
//将该元素的默认值转换为存储的
//来自数据对象的值:
document.getElementById(key).defaultValue=data[key];
})
}
},
“集合”:函数(e){
//因为我们将这个函数绑定到一个元素
//使用addEventListener,偶数通过
//因此,我们自动调用event.preventDefault()
//要防止元素的默认操作,
//对于窗体元素上的按钮,默认操作
//可能导致页面重新加载,我们不希望:
e、 预防默认值();
//查找要存储的相关表单字段:
var fields=document.querySelectorAll(“#用户名、#名称、#电子邮件、#密码”),
//转换从返回的HTMLCollection
//将document.querySelectorAll()放入数组中,
//使用Array.from()如果可用或,
//否则,一种旧的方法
//使用Array.prototype.slice()转换
//HTMLCollection到数组中:
fieldArray=Array.from?Array.from(字段):Array.prototype.slice.call(字段,0),
//初始化对象以存储
//临时物业:
存储={};
//如果元素数组中的每个元素都具有
//带有
//长度>0时,我们继续:
if(fieldArray.every)函数(el){
返回(el.value | | el.defaultValue).trim().length;
})) {
//在fieldArray上迭代:
fieldArray.forEach(函数(输入){
//如果元素的值,
//修剪后(移除导程和导程)
//尾随空格)有一个长度
//大于0(0为假):
if(input.value.trim().length){
//我们将值的键设置为
//存储到当前服务器的id
//元素,并存储
//具有该键的对象中的值:
存储[input.id]=input.value;
//我们还删除了“error”类-
//名称(如果元素具有该类):
input.classList.remove('error');
}否则{
//否则,我们将该值设置为该值
//以默认值保存:
input.value=input.defaultValue;
//添加“错误”类名:
input.classList.add('error');
//并将defaultValue存储在
//对象,因为对象本身
//将覆盖存储的对象
//所以我们需要显式地重新存储
//要防止为空的旧值
//参赛作品:
存储[input.id]=input.defaultValue;
}
});
//在这里,我们使用
//“data”的键和作为JSON字符串的值
//由“存储”对象形成:
window.localStorage.setItem('data',JSON.stringify(store));
//否则,鉴于我们没有预先存在的数据
//存储,我们不存储任何提供的数据,并添加
//“error”类名称到每个尚未指定的字段
//保留一个值(请注意,我不是在测试有效性
//价值观,仅仅是存在):
}否则{
//使用Array.prototype.filter()筛选数组
//只保留其值的元素,或
//defaultValue在修剪后为0:
fieldArray.filter(函数(el){
//从中删除“错误”类名
//每个要素:
el.classList.remove('error');
return(el.value | | el.defaultValue).trim().length==0;
}).forEach(功能(el){
//将“error”类名添加到每个
//从过滤器中保留的元素:
el.classList.add('error');
});
}
//纯粹是为了调试,这样您就可以看到
//正在保存;保存后(显然)将其删除
//快乐的:
document.getElementById('result').textContent=window.localStorage.getItem('data');
},
//清除功能,允许用户
//清空/删除其存储的数据:
“清除”:函数(e){
//我们再次使用event.preventDefault()来
//防止默认操作:
e、 预防
{"username":"hello89","name":"jane lim","password":"pass","email":"h@mail.com"} 
// making an object comprised of functions,
// in order to group related functions together:
var userData = {
  'get': function() {
    // here we retrieve the stored data (stored with
    // the key of 'data'):
    var data = window.localStorage.getItem('data');

    // typically retrieving an item that doesn't exist
    // will store null as the value of the variable to
    // which that item should be assigned, but here we
    // check for undefined as well (just to be sure):
    if (null === data || 'undefined' === typeof data) {
      // we exit the function here, since there's nothing
      // to be done with an empty/null data variable:
      return false;
    } else {

      // otherwise, if we have data, then we pass that
      // JSON string to JSON.parse() to turn it into
      // an iterable object:
      data = JSON.parse(data);
    }

    // we should have data at this point (since if we
    // we didn't we should have exited the function),
    // but I really like to be sure:
    if (data) {

      // retrieving an Array of keys from the data
      // object, and iterating over that array with
      // Array.prototype.forEach():
      Object.keys(data).forEach(function(key) {
        // 'key' : the first argument is a reference
        //         to the current array-element of
        //         the array of keys over which
        //         we're iterating.

        // we retrieve the element from the document with
        // the id matching the key, and assign the
        // defaultValue of that element to the stored
        // value from the data Object:
        document.getElementById(key).defaultValue = data[key];
      })
    }
  },
  'set': function(e) {
    // because we're binding this function to an element
    // using addEventListener the even is passed through
    // automatically, therefore we call event.preventDefault()
    // to prevent the default action of the element,
    // for a button on a form element that default action
    // may cause a page reload, which we don't want:
    e.preventDefault();

    // finding the relevant form fields to be stored:
    var fields = document.querySelectorAll('#username, #name, #email, #password'),
      // converting the HTMLCollection returned from
      // document.querySelectorAll() into an Array,
      // using Array.from() if it's available or,
      // otherwise, an older approach which calls
      // Array.prototype.slice() to convert the
      // HTMLCollection into an Array:
      fieldArray = Array.from ? Array.from(fields) : Array.prototype.slice.call(fields, 0),

      // initialising an Object to store the
      // properties temporarily:
      store = {};

    // if every element in the array of elements has
    // a truthy trimmed value, or defaultValue, with
    // a length > 0 we go ahead:
    if (fieldArray.every(function(el) {
        return (el.value || el.defaultValue).trim().length;
      })) {
      // iterating over the fieldArray:
      fieldArray.forEach(function(input) {

        // if the value of the <input> element,
        // once trimmed (removing leading and
        // trailing white-space) has a length
        // greater than 0 (0 is falsey):
        if (input.value.trim().length) {

          // we set the key of of the value to
          // store to the id of the current
          // <input> element, and store the
          // value in the object with that key:
          store[input.id] = input.value;

          // we also remove the 'error' class-
          // name if the element has that class:
          input.classList.remove('error');
        } else {

          // otherwise, we set the value to that
          // held in the defaultValue:
          input.value = input.defaultValue;

          // add the 'error' class-name:
          input.classList.add('error');

          // and store the defaultValue in the
          // Object, since the Object itself
          // will overwrite the stored Object
          // so we need to explicitly re-store
          // the old value to prevent empty
          // entries:
          store[input.id] = input.defaultValue;
        }
      });

      // here we store the data in localStorage with the
      // key of 'data' and the value as the JSON string
      // formed by the 'store' Object:
      window.localStorage.setItem('data', JSON.stringify(store));

      // otherwise, given that we have no pre-existing data to
      // store, we don't store any supplied data and we add an
      // 'error' class-name to each field that doesn't yet
      // hold a value (note that I'm not testing for validity
      // of values, simply existence):
    } else {

      // using Array.prototype.filter() to filter the Array
      // of elements to keep only those whose value, or
      // defaultValue, is 0 once it's trimmed:
      fieldArray.filter(function(el) {
        // removing the 'error' class-name from
        // each element:
        el.classList.remove('error');
        return (el.value || el.defaultValue).trim().length === 0;
      }).forEach(function(el) {
        // adding the 'error' class-name to each of the
        // elements that are retained from the filter:
        el.classList.add('error');
      });
    }

    // purely for debuggging, so that you can see what's
    // being saved; remove this (obviously) once you're
    // happy:
    document.getElementById('result').textContent = window.localStorage.getItem('data');
  },

  // the clear function, to allow the user to
  // empty/remove their stored data:
  'clear': function(e) {
    // again we use event.preventDefault() to
    // prevent the default action:
    e.preventDefault();

    // and then we clear the localStorage:
    window.localStorage.clear();

    // we could, instead, simply use:
    // window.localStorage.removeItem('data');
    // to do the same thing, but this will only
    // remove the 'data' item, and leave anything
    // and everything else; which seems like a
    // bad UI based on user-expectation.

    // clearing the visible data from the <form>
    // with which this <button> element was associated:
    this.form.reset();
  }
}

// binding the named functions (note the lack of parentheses) to
// the named events of the elements:
document.querySelector('#save').addEventListener('click', userData.set);
document.querySelector('#clear').addEventListener('click', userData.clear);

// calling the get() function on page-load:
userData.get();