记住带有localstorage onclick的复选框 [英] Remember checkbox with localstorage onclick

查看:117
本文介绍了记住带有localstorage onclick的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Chrome扩展程序创建一个选项页面.第一部分将值设置为本地存储.选中true,取消选中false.如果用户在其他时间回来,第二部分应该更新复选框,并且设置将应用于该复选框.

I am trying to create an options page for a Chrome extension. The first part sets the value in to local storage. Check for true and uncheck for false. The second part is supposed to update the check box if the user comes back at some other time and the settings will apply to the check box.

我的问题是,当用户刷新或关闭窗口并返回时,复选框永远不会被选中,但是本地存储将变为true或false.我如何做到这一点,以便用户可以选中该框,并且该框将在用户以后返回或刷新esthe页面时保留.

My problem is that the check box is never check when the user refreshes or closes the window and comes back, but the local storage will change to true or false. How do I make it so that the user can check the box and it will stay when the user returns at a later time or refresh esthe page.

    setStatus = document.getElementById('stat');
    setStatus.onclick = function() {
        if(document.getElementById('stat').checked) {
            localStorage.setItem('stat', "true");
        } else {
            localStorage.setItem('stat', "false");
        }
    }


getStstus = localStorage.getItem('stat');
    if (getStstus == "true") {
        console.log("its checked");
        document.getElementById("stat").checked;
    } else {
        console.log("its not checked");
    }

推荐答案

更改:

document.getElementById("stat").checked;

收件人:

document.getElementById("stat").setAttribute('checked','checked');

将解决此问题.由于添加.checked时,实际上只是检查复选框是否为选中状态.

Would fix this. Since when adding .checked, that actually just checks if the checkbox is check.

您也可以这样做:

document.getElementById("stat").checked=true;   

做同样的事情.

请注意,您需要更改 document.getElementById("stat").checked.

Please note that you need to change the second document.getElementById("stat").checked.

getStstus = localStorage.getItem('stat');
    if (getStstus == "true") {
        console.log("its checked");
        document.getElementById("stat").setAttribute('checked','checked');
    } else {
        console.log("its not checked");
    }​

JsFiddle示例

这篇关于记住带有localstorage onclick的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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