如何根据用户之前的值设置默认值
How to set a default value based on user's previous value
我想要一个基于用户之前输入的默认值。例如,如果在输入中输入“5”,我想在刷新页面时看到该输入的值为 5,但是如果输入 6,我希望默认值为 6。谢谢(我是初学者)
使用本地storage:
localStorage = window.localStorage;
localStorage.setItem('inputDefault', '5');
let inputDefault = localStorage.getItem('inputDefault');
这是我快速创建的一个更实际的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Storage Example</title>
<script type="text/javascript">
function setLocalStorageValue()
{
let myNumberInputField = document.getElementById('myNumberInput');
let myNewValue = myNumberInputField.value;
let localStorage = window.localStorage;
localStorage.setItem('defaultValue', myNewValue);
}
function getLocalStoredValue()
{
let localStorage = window.localStorage;
let defaultValue = localStorage.getItem('defaultValue');
let myNumberInputField = document.getElementById('myNumberInput');
myNumberInputField.value = defaultValue;
}
</script>
</head>
<body onload="getLocalStoredValue()">
<label>My Number Input
<input type="number" id="myNumberInput" value="0" onchange="setLocalStorageValue()">
</label>
</body>
</html>
这是否回答了您的问题?请注意我是如何在相关输入的 onchange 事件上写回本地存储的,并且当 html 的主体加载时我从本地存储中读取。
我想要一个基于用户之前输入的默认值。例如,如果在输入中输入“5”,我想在刷新页面时看到该输入的值为 5,但是如果输入 6,我希望默认值为 6。谢谢(我是初学者)
使用本地storage:
localStorage = window.localStorage;
localStorage.setItem('inputDefault', '5');
let inputDefault = localStorage.getItem('inputDefault');
这是我快速创建的一个更实际的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Storage Example</title>
<script type="text/javascript">
function setLocalStorageValue()
{
let myNumberInputField = document.getElementById('myNumberInput');
let myNewValue = myNumberInputField.value;
let localStorage = window.localStorage;
localStorage.setItem('defaultValue', myNewValue);
}
function getLocalStoredValue()
{
let localStorage = window.localStorage;
let defaultValue = localStorage.getItem('defaultValue');
let myNumberInputField = document.getElementById('myNumberInput');
myNumberInputField.value = defaultValue;
}
</script>
</head>
<body onload="getLocalStoredValue()">
<label>My Number Input
<input type="number" id="myNumberInput" value="0" onchange="setLocalStorageValue()">
</label>
</body>
</html>
这是否回答了您的问题?请注意我是如何在相关输入的 onchange 事件上写回本地存储的,并且当 html 的主体加载时我从本地存储中读取。