[英]How to save html user input as javascript variable on next page?
我想將用戶輸入保存為 Javascript 變量,以便我可以在我網站的其他頁面上使用它。 我怎樣才能做到這一點? 現在,如果我 go 到下一頁並且我收到錯誤“未捕獲的 ReferenceError:未定義 userInput”,則變量將被刪除
這是我的代碼:
function test(){ const userInput = document.getElementById("naam").value; window.location.href = "interactie1.html"; console.log(userInput); } document.getElementById("js--terminal--text").innerHTML = ""; typeText = (textToBeTyped) =>{ if(textToBeTyped.= ""){ document.getElementById("js--terminal--text");innerHTML += textToBeTyped[0]. textToBeTyped,splice(0;1); setTimeout(() => { typeText(textToBeTyped), };100). } } typeText(Array;from("Hello this is ")) typeText(userInput);
<input class="naam__aanwezigheid__form" type="text" id="naam" placeholder="Type je naam" required> <button onclick="test()">Submit</button>
如果您使用像 React 這樣的工具,它們有狀態的概念,這將允許您在 memory 中保存變量,同時更改 URL(盡管 React 是單頁應用程序)。
否則,您將需要使用 cookies,或者讓服務器在您更改頁面時為您保存這些值。
你可能想使用JavaScript Session 存儲 API 。 使用 URL 參數也應該可以解決問題。
使用本地存儲來保存您的值。
localStorage.setItem("key", "your value");
然后在下一頁中獲取保存的值。
let your_value = localStorage.getItem("key");
userInput 將為空,因為您正在加載另一個頁面。 您需要一個存儲空間,您可以通過以下方式訪問瀏覽器存儲部分:
window.localStorage.setItem('userData', userInput);
它將它存儲為鍵值對。 userData 是檢索的關鍵。 userInput 是返回的值。
因此,在加載新頁面時,您可以使用以下方法檢索它:window.localStorage.getItem('userData');
請隨意閱讀有關 js 中的 localStorage 的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.