如何将setting.html中的JavaScript变量传递到index.html?
如何在HTML页面间传递表单输入值
我已经成功在setting.html中获取表单输入数据并通过console.log输出,现在需要将该变量传递到另一个文件index.html中,请问该如何实现?
初始代码
setting.html
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>settings</title> </head> <body> <form action=index.html> <input id="userinput" type="text"> <button onclick="myfunction()">Click me</button> </form> </body> <script> var theinput=''; function myfunction() { theinput=document.getElementById("userinput").value; console.log(theinput); } </script> </html>
index.html
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="settings.html"></script> </head> <body> <a href="setting.html">settings</a> <button onclick="theFunction()">generate pdf</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script> <script> input=document function theFunction() { var num = 'this is....'; console.log(num); const pdf = new jsPDF(); pdf.text(num,10,10); pdf.save('a4.pdf'); } </script> </html>
实现方案(使用localStorage)
通过浏览器的localStorage可以在同一域名下的页面间共享数据,下面是修改后的可运行代码:
更新后的setting.html
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>settings</title> </head> <body> <h1>Settings</h1> <form> <input id="userinput" name="input" type="text"> <button type="button" class="btn-submit">Submit</button> </form> <script> let btn = document.querySelector(".btn-submit") let userinput = document.querySelector("#userinput") btn.addEventListener("click",function(){ localStorage.setItem("userinput",userinput.value) location.href = "index.html"; }); </script> </body> </html>
更新后的index.html
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <a href="setting.html">settings</a> <button onclick="theFunction()">generate pdf</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script> <script> input=document function theFunction() { // 读取localStorage中存储的用户输入值,没有则用默认文本 var num = localStorage.getItem("userinput") || 'this is....'; console.log(num); const pdf = new jsPDF(); pdf.text(num,10,10); pdf.save('a4.pdf'); } // 页面加载时读取并打印存储的值 let userInput = localStorage.getItem("userinput") || ""; console.log(userInput); </script> </html>
逻辑说明
- 在setting.html中,点击提交按钮时,将输入框的值存入
localStorage的userinput键中,随后跳转到index.html - 在index.html中,通过
localStorage.getItem("userinput")读取存储的值,可直接在生成PDF等业务逻辑中使用该值 localStorage存储的数据会持久保留在浏览器中(除非主动清除),适合存储这类跨页面保留的配置类数据
内容的提问来源于stack exchange,提问作者ofey
相关产品推荐
相关产品推荐

