首页 > 解决方案 > 无法使用本地存储中的 JavaScript 填充电子邮件字段

问题描述

我有两个文件 test.html 和 test2.html 我可以保存表单的值,但无法填写 test2.html 表单中的输入字段。

测试.html

    <script  type="text/javascript">
  function store(){
     var inputEmail= document.getElementById("email");

     localStorage.setItem("email", inputEmail.value);
    }
</script>
<form action="test2.html" class="form-login"  method="post" /> 
<input name="email" type="email" id="email" required="" placeholder="Email" />

<button onclick="store()" type="button">StoreEmail</button>

测试2.html

      <script type="text/javascript">
      function get(){

         var storedValue = localStorage.getItem("email");

         document.getElementById("email").innerHTML = storedValue;
         document.getElementById("email").value = storedValue;

        }
    </script>
    <p id="email">qqqqqq</p>
    <form action="" class="form-login"  method="post" /> 
    <input name="email" type="email" id="email" placeholder="Email" />

<button onclick="get()" type="button">getEmail</button>

当我单击 getEmail 按钮时,段落会更改,但电子邮件输入字段不会随值更改。请帮忙。

标签: javascripthtml

解决方案


每个 DOM 节点的 id 在整个 DOM 中应该是唯一的

document.getElementById 总是返回第一个匹配的 dom 节点


推荐阅读