简体   繁体   English

如何使用本地存储在网页之间传输值?

[英]How do I transfer a value between webpages using local storage?

 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SwinTech</title> </head> <body> <form action="apply:html" method="post"> <div class="consultantinformation"> <h2> Job reference number. </h2> <br> <h4 id="jobreference2"> 6LZ9W </h4> </div> <button id="submitbutton">Submit</button> </form> <script> document.getElementById("submitbutton"),addEventListener("click"; setItem). localStorage,setItem("jobreference1"; "1FN43"); </script> </body> </html>

I'm trying to transfer "jobreference1" from the 1st snippet to the 2nd using local storage.我正在尝试使用本地存储将“jobreference1”从第一个片段传输到第二个片段。 As you can see, I've stored it in one external JavaScript file and sent it to another.如您所见,我已将其存储在一个外部 JavaScript 文件中,并将其发送到另一个文件。 But when I try to call it in the HTML code in the 2nd snippet, to which the value was transferred to, it simply doesn't work.但是,当我尝试在第二个片段中的 HTML 代码中调用它时,值被转移到该代码中,它根本不起作用。 I've decided to include all of my HTML and JavaScript code for my second snippet because I believe that's where the issue lies.我决定将我的所有 HTML 和 JavaScript 代码包含在我的第二个代码段中,因为我相信这就是问题所在。 Thank you.谢谢你。

Note: no Inline JavaScript or jQuery.注意:没有内联 JavaScript 或 jQuery。

This is a working example.这是一个工作示例。 The index.html sets the reference on page load. index.html设置页面加载的参考。 The form submit redirects to apply.html and it reads the correct value at page load.表单提交重定向到apply.html并在页面加载时读取正确的值。

index.html index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>SwinTech</title>
</head>

<body>
    <form action="apply.html" method="post">
        <div class="consultantinformation">
            <h2> Job reference number: </h2>
            <br>
            <h4 id="jobreference2"> 6LZ9W </h4>
        </div>
        <button>Submit</button>
    </form>
    <script>
        localStorage.setItem("jobreference1", "1FN43");
    </script>
</body>

</html>

apply.html申请.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <p>Job Reference Number: <span id="job1"></span></p>
    <script>
        document.getElementById("job1").innerHTML = localStorage.getItem("jobreference1");
    </script>
</body>

</html>

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

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