使用localStorage在页面之间传递数据

时间:2016-04-29 23:16:09

标签: javascript database html5 local-storage

我使用localStorage在页面之间传递数据。页面表单名称为personalFormparentsFormrelationsFormgenealogyForm

我无法将relationsForm的数据显示在genealogyForm上。我也无法删除genealogyForm上的数据。

这是代码。

function CheckBrowser() {
  if ('localStorage' in window && window['localStorage'] !== null) {
    // we can use localStorage object to store data
    return true;
  } else {
    return false;
  }
}
window.onload = function() {
  // Add an event listener for form submissions
  document.getElementById('personalForm').addEventListener('submit', function() {
    // Get the value of the name field.
    var firstName = document.getElementById('myFirstName').value;
    var lastName = document.getElementById('myLastName').value;
    var birthDate = document.getElementById('myBirthDate').value;
    var gender = document.getElementById('myGender');
    var name = firstName + " " + lastName;
    // Save the name in localStorage.
    localStorage.setItem('name', name);
  });
  document.getElementById('parentsForm').addEventListener('submit', function() {
    var fatherFirstName = document.getElementById('myFatherFirstName').value;
    var fatherLastName = document.getElementById('myFatherLastName').value;
    var motherFirstName = document.getElementById('myMotherFirstName').value;
    var motherLastName = document.getElementById('myMotherLastName').value;
    var fatherName = fatherFirstName + " " + fatherLastName;
    var motherName = motherFirstName + " " + motherLastName;
    localStorage.setItem('father', fatherName);
    localStorage.setItem('mother', motherName);
  });
  document.getElementById('relationsForm').addEventListener('submit', function() {
    var spouseFirstName = document.getElementById('mySpouseFirstName').value;
    var spouseLastName = document.getElementById('mySpouseLastName').value;
    var numberChildren = document.getElementById('myNumberChildren').value;
    var spouseName = spouseFirstName + " " + spouseLastName;
    localStorage.setItem('spouse', spouseName);
    localStorage.setItem('children', numberChildren);
  });
}
(document.getElementById("relationsCreate").addEventlistener("click", function addMember() {
    var name = localStorage.getItem('name');
    var father = localStorage.getItem('father');
    var mother = localStorage.getItem('mother');
    var spouse = localStorage.getItem('spouse');
    var children = localStorage.getItem('children');
    document.getElementById('table').innerHTML = "Your name is " + name + "!";
  }
  (document.getElementById("myDelete").addEventListener("click", function deleteMember() {
    localStorage.removeItem('name');
    localStorage.removeItem('father');
    localStorage.removeItem('mother');
    localStorage.removeItem('spouse');
    localStorage.removeItem('children');
  })),
  false));

0 个答案:

没有答案