繁体   English   中英

为什么这个本地存储代码不起作用?

[英]Why doesn't this local storage code work?

这是我的 index.html 代码

<form action = "indo.html">
      <input type = "text" id = "tex">
      <button id = "tex">Submit</button>

    </form>
    <script>

      var o = document.getElementById("tex").value;
      localStorage.setItem("three", o);
    </script>

这是我的代码 indo.html

<script>
  var n = localStorage.getItem("three");
  document.write("Welcome "+n);
</script>

实际上它的工作。但该值为空。设置输入的初始值。因为它在页面加载时的设置值不在表单提交之后

尝试这个

<form action="indo.html">
  <input type="text" id="tex" value="something">
  <button id="tex">Submit</button>

</form>
<script>
  var o = document.getElementById("tex").value;
  localStorage.setItem("three", o);
</script>

indo.html

<script>
  var n = localStorage.getItem("three");
  document.write("Welcome " + n);
</script>

如果要将数据保存到本地存储中,我建议使用以下代码:

<form >
  <input type = "text" id = "tex">
  <button id = "texb">Submit</button>
</form>

function fun_sub(){
 const val = document.getElementById("tex").value;
  localStorage.setItem("three", val);
  console.log(localStorage.getItem("three"));
  window.open("/indo.html", "_self");
}

在你的代码中,输入元素和按钮元素的name id是相同的,如果你在javascript中调用getElementById,这个错误会返回错误,你必须考虑在你写代码的时候,你想在渲染页面后再次调用代码。 你应该在一个函数中调用它。

暂无
暂无

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

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