如何基于用户的先前值设置默认值 [英] How to set a default value based on user's previous value

查看:96
本文介绍了如何基于用户的先前值设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户输入的内容获得默认值。例如,如果在输入中我输入 5,那么我希望在刷新页面时看到该输入的值为5,但是如果输入6,则我希望默认值为6。谢谢(我是begginer)

I want to have a default value based on what the user put before. For example, if in an input I put '5' I want to see that the value of that input is 5 when I refresh the page, but if I put 6 I want the default value to be 6. Thanks (i'm a begginer)

推荐答案

使用本地存储

localStorage = window.localStorage;
localStorage.setItem('inputDefault', '5');

let inputDefault = localStorage.getItem('inputDefault');

下面是一个更实际的例子,我很快就总结道:

Here's a more practical example I quickly whipped up:

<!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正文时从本地存储读取的。

Does this answer your question? Note how I am writing back to local storage on the onchange event of the input in question, and I read from local storage when the body of the html loads.

这篇关于如何基于用户的先前值设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆