使用JavaScript localStorage输入表单数据

时间:2016-10-12 01:14:28

标签: javascript html

我有两个简单表单的HTML页面。我想在用户点击“提交”时使用localStorage保存index.html的文本输入,并使该值显示在html1.html的文本字段中。我认为我的 retrieveName()函数的实现可能存在问题。可以改进哪些方法使其正常工作?

的index.html

width : x;

html1.html

<form name="form1" method="post" action="html1.html">
  <label>Name:
    <input type="text" id="fname" name="lastName" />
  </label>
  <input type="submit" name="submitName" value="Submit" onclick = "submitName()">

  <script>
    function submitName() {
      var userName = document.getElementById("fname");
      localStorage.setItem("lastName", userName.value);
    }
  </script>
</form>

2 个答案:

答案 0 :(得分:0)

localStorage.getItem("lastName");

这应该有效。您存储的密钥与检索值的密钥相同。

https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

答案 1 :(得分:0)

详细信息在代码段和PLUNKER中进行了评论。 由于SO上的沙箱是严格的,所以Snippet将无法正常运行,因此请查看Plunker。顺便说一下,主要问题是你没有使用与getItem()

相同的密钥setItem()

实施例

     On the first page: setItem('CAT', animal.value)

     On the second page: getItem('DOG'); 

那是你基本上做的。在您的案例中,'CAT' = "lastName"'DOG' = "textValue"具体。

注意:你不应该改变你的问题中的错误,这会让读者感到困惑。

INDEX

&#13;
&#13;
<!doctype html>
<html>

<head>
  <meta charset='utf-8'>
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
</head>

<body onload='retrieveName()'>
  <form name="form2">
    <fieldset>
      <legend>HTML1</legend>
      <label>Last Name:
        <input type="text" id="lastName" />
      </label>
      <input type="submit" id="submitLastName" value="Save" />
    </fieldset>
    <p>(2) Click <kbd>Save</kbd>
    </p>
  </form>
  <script>
    // Reference the input lastName
    var x = document.getElementById("lastName");

    /*
    | Retrieve the stored data with the 
    | CORRECT KEY I.E. dataName
    | Assign the value of dataName as the 
    | value of x
    */
    function retrieveName(e) {
      var text = localStorage.getItem("dataName");
      x.value = text;
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;

HTML1

&#13;
&#13;
<!doctype html>
<html>

<head>
  <meta charset='utf-8'>
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
</head>

<body onload='retrieveName()'>
  <form name="form2">
    <fieldset>
      <legend>HTML1</legend>
      <label>Last Name:
        <input type="text" id="lastName" />
      </label>
      <input type="submit" id="submitLastName" value="Save" />
    </fieldset>
    <p>(2) Click <kbd>Save</kbd>
    </p>
  </form>
  <script>
    // Reference the input lastName
    var x = document.getElementById("lastName");

    /*
    | Retrieve the stored data with the 
    | CORRECT KEY I.E. dataName
    | Assign the value of dataName as the 
    | value of x
    */
    function retrieveName(e) {
      var text = localStorage.getItem("dataName");
      x.value = text;
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;