繁体   English   中英

将 localstorage 数据携带到多个 HTML

[英]Carry localstorage data to more than one HTML

我无法将此表单中的本地存储数据传输到多个 html。 下面的代码可以正常工作(在两个 html 的正文中都使用 onload="setData()"),用户将文本输入到表单中,当提交时,它被传递到 main2.html。 但是,我需要四个提交按钮来将该数据传送到单独的 html 中。

我知道这个功能是因为 action="main2.html" 在表单标签中。 这显然意味着我不能使用相同的表单将此数据发送到单独的页面。 有没有办法解决这个问题,或者我是否需要为每个页面提供单独的表格?

发送页面 HTML:

<form id="form" method="GET" action="main2.html">
      <input
        class="name-input"
        type="text"
        placeholder="YOUR NAME"
        name="name"
        id="name"
      />
      <input
        class="button1"
        type="button"
        value="Submit"
        onclick="submitForm()"
      />
      <input
        class="button2"
        type="button"
        value="Submit"
        onclick="submitForm()"
      />
      <input
        class="button3"
        type="button"
        value="Submit"
        onclick="submitForm()"
      />
      <input
        class="button4"
        type="button"
        value="Submit"
        onclick="submitForm()"
      />
    </form>

发送页面 JS

    <script>
      function submitForm() {
        if (typeof localStorage != "undefined") {
          localStorage.name = document.getElementById("name").value;
        }
        document.getElementById("form").submit();
      }
    </script>

接收页面 HTML

    <div class="hey">
      <h1 id="show" class="name-placeholder">Luke Jones's</h1>
    </div>

接收页面 JS

    <script>
      function setData() {
        if (typeof localStorage != "undefined") {
          document.getElementById("show").innerHTML = localStorage.name;
        }
      }
    </script>

这可能非常混乱,但我通过听取上面的评论并删除表单,并为将它们链接到单独页面的按钮添加 JS 函数来让它工作。 还保留原始问题的发送和接收 JS。

 <input
        method="GET"
        class="name-input"
        type="text"
        placeholder="YOUR NAME"
        name="name"
        id="name"
      />
      <input
        class="button1"
        type="button"
        value="Page1"
        onclick="myFunction1(); submitForm();"
      />
      <input
        class="button2"
        type="button"
        value="Page2"
        onclick="myFunction2(); submitForm();"
      />

     function myFunction1() {
        window.location.href = "main2.html";
      }

      function myFunction2() {
        window.location.href = "main3.html";
      }

暂无
暂无

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

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