繁体   English   中英

复选框和本地存储

[英]Checkboxes and localStorage

如果您愿意,我有一个任务列表,我正在尝试创建复选框,当我返回页面时,这些复选框仍然存在,但关闭浏览器或硬刷新会杀死我的选择。 我找到了保存单个复选框的代码,但是如何遍历不同的框并在下次输入时保留它们? 这似乎是一个非常简单的过程,但我对 javascript 非常陌生......我可以在 vbscript 中轻松做到这一点,但我希望它可以在任何地方工作,而不仅仅是 IE!

这一切都是新手,所以请保持温柔。

<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
  function save() {
    //enter iteration sequence
    var checkbox = document.getElementById("box");
    localStorage.setItem("box", checkbox.checked);
  }

//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>

要检索所有元素,您可以使用document.querySelectorAll并将执行该工作的过滤器作为参数传递。 在这种情况下,您希望检索type属性值等于checkbox所有htlm元素。 在检索到所有具有type="checkbox"元素后,您应该遍历列表的所有元素。 对于每个元素,您应该将复选框的 id 存储为key ,并将checked的选中状态存储为 localstorage 中的value

下面是代码:

    <script>
        save = function(){
            var list = document.querySelectorAll(`[type*="checkbox"]`);
            list.forEach( el => {
                localStorage.setItem(el.id, el.checked);
                console.log(el.id,el.checked);
            })

        }
    </script>

下面是使用我们存储在 localstorage 中的值更新复选框的代码。

            var list = document.querySelectorAll(`[type*="checkbox"]`);
            list.forEach( el => {
            var checked = JSON.parse(localStorage.getItem(el.id));
            document.getElementById(el.id).checked = checked;
            });

如果要使用cookie来存储信息而不是本地存储。 更多信息链接: https : //www.guru99.com/cookies-in-javascript-ultimate-guide.html


function createCookie(cookieName, cookieValue, daysToExpire) {
    var date = new Date();
    date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
    document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}

function accessCookie(cookieName) {
    var name = cookieName + "=";
    var allCookieArray = document.cookie.split(';');
    for (var i = 0; i < allCookieArray.length; i++) {
        var temp = allCookieArray[i].trim();
        if (temp.indexOf(name) == 0)
            return temp.substring(name.length, temp.length);
    }
    return "";
}

本地存储版本

<html>
<head>
</head>
<body>
    <div>
        <input type="checkbox" id="whatever-1" />This task
        <input type="checkbox" id="whatever-2" />This task
        <input type="checkbox" id="whatever-3" />This task
        <input type="checkbox" id="whatever-4" />This task
        <input type="checkbox" id="whatever-5" />This task
        <input type="button" value="Save" onclick="save();" />
    </div>
        <script>
            window.onload= function(){
                    var list = document.querySelectorAll(`[type*="checkbox"]`);
                    list.forEach( el => {
                        var checked = JSON.parse(localStorage.getItem(el.id));
                        document.getElementById(el.id).checked = checked;
                    });
            }
            save = function(){
            var list = document.querySelectorAll(`[type*="checkbox"]`);
            list.forEach( el => {
                localStorage.setItem(el.id, el.checked);
                console.log(el.id,el.checked);
            })

        }
    </script>
</body>
</html>

带有 Cookie 的版本

<html>
<head>
</head>
<body>
    <div>
        <input type="checkbox" id="whatever-1" />This task
        <input type="checkbox" id="whatever-2" />This task
        <input type="checkbox" id="whatever-3" />This task
        <input type="checkbox" id="whatever-4" />This task
        <input type="checkbox" id="whatever-5" />This task
        <input type="button" value="Save" onclick="save();" />
    </div>
        <script>
            window.onload= function(){
                    var list = document.querySelectorAll(`[type*="checkbox"]`);
                    list.forEach( el => {
                        var checked = JSON.parse(accessCookie(el.id));
                        document.getElementById(el.id).checked = checked;
                    });
            }
            save = function(){
                var list = document.querySelectorAll(`[type*="checkbox"]`);
                list.forEach( el => {
                    createCookie(el.id, el.checked,1);//1 is the day to expire
                    console.log(el.id,el.checked);
                })
            }
            function createCookie(cookieName, cookieValue, daysToExpire) {
                var date = new Date();
                date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
                document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
            }

            function accessCookie(cookieName) {
                var name = cookieName + "=";
                var allCookieArray = document.cookie.split(';');
                for (var i = 0; i < allCookieArray.length; i++) {
                    var temp = allCookieArray[i].trim();
                    if (temp.indexOf(name) == 0)
                        return temp.substring(name.length, temp.length);
                }
                return "";
            }
    </script>
</body>
</html>

只需将不同的 id 传递给document.getElementById 确保对localStorage.setItem使用不同的键,以免覆盖不同的值。

var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;

您可以为每个项目单独执行此操作,也可以获取特定类的所有元素。 然后循环遍历元素并使用它们的 id 作为本地存储键。


或者,您可以使用for循环和循环来保存尽可能多的项目

在每次save您可以创建一个带有复选框标识和值的对象,将 t 保存在localStorage ,重新加载时,通过单个键获取整个对象,解析它,循环并设置值

function save() {
  //enter iteration sequence
  var checkboxes = document.querySelectorAll("input[type=checkbox]");
  var obj = {};
  for (i = 0; i < checkboxes.length; i++) {
    obj[checkboxes[i].id] = checkboxes[i].checked
  }
  localStorage.setItem("box", JSON.stringify(obj));
}

//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);

如果您传递正确的输入 ID,您的代码也能正常工作,但存在一个问题,即对于每个输入,您必须添加变量,您也可以为此使用 for 循环。

您的代码与修复脚本

 <input type="checkbox" id="whatever-1" />This task <input type="checkbox" id="whatever-2" />This task <input type="button" value="Save" onclick="save();" /> <script> function save() { var checkbox = document.getElementById("whatever-1"); localStorage.setItem("whatever-1", checkbox.checked); var checkbox2 = document.getElementById("whatever-2"); localStorage.setItem("whatever-2", checkbox2.checked); } var checked = JSON.parse(localStorage.getItem("whatever-1")); document.getElementById("whatever-1").checked = checked; var checked = JSON.parse(localStorage.getItem("whatever-2")); document.getElementById("whatever-2").checked = checked; </script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM