首页 > 解决方案 > 即使在 html 中重新加载页面后,我应该如何使输入永久化并使输入保持不变?

问题描述

我应该如何使输入永久化?例如,如果我输入“Hello world”它应该说“hello world”并且“hello world”即使在重新加载后也应该在那里

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="content"></p>
    <input type="text" id="userInput">
    <script>
        function getInputFromTextBox() {
    let input = document.getElementById("userInput").value;
document.getElementById("content").innerHTML = input;
     
}



    </script>
 
    <button onclick="getInputFromTextBox()">submit</button>
</body>

</html>

标签: javascripthtmlcss

解决方案


您可以使用本地存储

// JAVASCRIPT

// Getting the value from localStorage
// The "key" here need to be the same defined below on the save() function
const getValue = localStorage.getItem("key");
if (getValue) {
    document.getElementById("inputId").value = getValue;
}

function save() {
    const setValue = document.getElementById("inputId").value;
    // Here you can set 'key' with any name you like
    // Setting the value in localStorage
    localStorage.setItem("key", setValue);
}
<!-- HTML -->
<input type="text" id="inputId" />
<button onclick="save()">save value</button>


推荐阅读