简体   繁体   English

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

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

This is my code for index.html这是我的 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>

This is my code for indo.html这是我的代码 indo.html

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

Actually its working.But the value is empty.set Initial value on input.Because its set value on page load not after the form submit实际上它的工作。但该值为空。设置输入的初始值。因为它在页面加载时的设置值不在表单提交之后

Try this尝试这个

<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 indo.html

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

If you want save data into local-storage i suggest below code:如果要将数据保存到本地存储中,我建议使用以下代码:

<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");
}

In your code, name id of input element and button element is same, this mistake return error if you call getElementById in javascript,and you must consider that when you write a code and you want call code again after render page.在你的代码中,输入元素和按钮元素的name id是相同的,如果你在javascript中调用getElementById,这个错误会返回错误,你必须考虑在你写代码的时候,你想在渲染页面后再次调用代码。 you should call it in a function.你应该在一个函数中调用它。

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

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