如何将html用户输入保存为下一页的javascript变量



我想将用户输入保存为Javascript变量,这样我就可以在网站的其他页面上使用它。我该怎么做?现在,如果我转到下一页并得到错误";未捕获的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这样的工具,它们有状态的概念,这将允许您在更改URL时将变量保存在内存中(不过React是一个单页应用程序(。

否则,您将需要使用cookie,或者在更改页面时使用服务器为您保存这些值。

使用本地存储来保存您的值。

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的更多信息。

您可能需要使用JavaScript会话存储API。使用URL参数也可以。

最新更新