如何在触发事件后在本地存储中设置复选框状态



>我有一个默认选中的复选框输入,用于切换页面上元素的可见性。我希望用户在刷新页面时保存选项。

var c = document.createElement('input')
c.setAttribute("type", "checkbox")
c.checked = true
c.onclick = function(){
    if(c.checked) element.style.display = 'block'
    if(c.checked == false) element.style.display = 'none'
}
/* This code below saves the state of the checkbox,
 but never fires the event or updates the element */
c.checked = (localStorage.getItem('cchecked')== 'true');
c.onchange = function(){
    localStorage.setItem('cchecked', c.checked)
}

好吧,一个更完整的示例有效..

<!DOCTYPE html>
<html>
    <body>
        <hr id="line" />
        <script>
        var element = document.getElementById('line')
        var c = document.createElement('input')
        c.setAttribute("type", "checkbox")
        c.checked = true
        c.onclick = function(){
            if(c.checked) element.style.display = 'block'
            if(c.checked == false) element.style.display = 'none'
        }
        /* This code below saves the state of the checkbox,
         but never fires the event or updates the element */
        // c.checked = (localStorage.getItem('cchecked')== 'true');
        if (localStorage.getItem('cchecked')== 'true') {
            c.checked = true;
        }
        else if (localStorage.getItem('cchecked')== 'false') {
            c.checked = false;
        }
        c.onchange = function(){
            localStorage.setItem('cchecked', ( c.checked ? 'true' : 'false'))
        }
        if ( !c.checked) element.style.display = 'none'
        document.body.appendChild(c);
        </script>
    </body>
</html>

相关内容

  • 没有找到相关文章

最新更新