首页 > 解决方案 > Passing a variable between HTML pages using JavaScript

问题描述

I begin with having a user input their name into a text field on the first html page and then click a button to move to a second html page.

How do I store the user's inputed name as a variable that can be referenced on a differnt html page?

First HTML page

<input type = "text" id = "name">

<button onclick = "sv(); window.location.href = 'second.html'">Submit now</button>

JavaScript on First HTML page

function sv() {
sessionStorage.setItem("theirname", document.getElementById("name").value);
 }

Second HTML page

 <p id="output"></p>

JavaScript on Second HTML Page

document.getElementById("output").value = sessionStorage.getItem("theirname");

标签: javascripthtml

解决方案


您可以将数据存储到 localStorage

let input = document.getElementById('input'); 

setStorage = () => {
    localStorage.setItem('name', input.value);
}


//On your second HTML
getStorage = () => {
    localStorage.getItem('name');
}
<input type="text" id="input">
<button onclick="setStorage()">Go!</button>


推荐阅读