首页 > 解决方案 > 如何将html用户输入保存为下一页上的javascript变量?

问题描述

我想将用户输入保存为 Javascript 变量,以便可以在我网站的其他页面上使用它。我怎样才能做到这一点?现在,如果我转到下一页,该变量将被删除,并且出现错误“未捕获的 ReferenceError:未定义用户输入”

这是我的代码:

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>

标签: javascripthtml

解决方案


由于您正在更改页面,因此脚本已卸载,因此您无法访问这些变量。

也许你可以试试这个:会话存储

或者确保您首先加载了脚本以使用变量。


推荐阅读