javascript - 即使在 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>
解决方案
您可以使用本地存储
// 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>
推荐阅读
- php - 我想检查两个表是否所有内容都相似
- azure - 如何在 Azure ML 工作室设计器管道中使用模块?
- nuxt.js - 我如何从生产中阻止页面但在 nuxt 的开发中显示?
- sql - 无法识别日期“% {syslog_timestamp}”
- unity3d - 如何让物体只碰撞一次?
- python - 获取前 n 列并忽略 NaN
- scala - Scala,创建一个二维数组来管理用户
- sql - 最长公共子串、BigQuery、SQL
- scala - 如何读取 csv 文件并将值分配给 spark scala 中的变量
- wordpress - Woocommerce:当前类别的产品类别小部件