保持选中复选框状态,直到用户取消选中

keeping checked checkbox state until user unchecked

本文关键字:用户 取消 状态 复选框      更新时间:2023-09-26

目前,在移动页面时,我想保留我在上一页中选中的复选框的状态。我也尝试了一下自己,在网上查了一下。我为此找到了一些解决方案,但这并不好。下面是我找到的示例,但它只在 Firefox 上哄骗,而在 Chrome 上没有。

<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>Persist checkboxes</title>
<style>
button {
    margin-top: 8px;
}
</style>
</head>
<body>
<div>
    <label for="option1">Option 1</label> <input type="checkbox"
        id="option1">
</div>
<div>
    <label for="option2">Option 2</label> <input type="checkbox"
        id="option2">
</div>
<div>
    <label for="option3">Option 3</label> <input type="checkbox"
        id="option3">
</div>
<button>Check all</button>

<script
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script
    src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
    function handleButtonClick(button) {
        if ($(button).text().match("Check all")) {
            $(":checkbox").prop("checked", true)
        } else {
            $(":checkbox").prop("checked", false)
        }
        ;
        updateButtonStatus();
    }
    function updateButtonStatus() {
        var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
        $("button").text(allChecked ? "Uncheck all" : "Check all");
    }
    function updateCookie() {
        var elementValues = {};
        $(":checkbox").each(function() {
            elementValues[this.id] = this.checked;
        });
        elementValues["buttonText"] = $("button").text();
        $.cookie('elementValues', elementValues, {
            expires : 7,
            path : '/'
        })
    }
    function repopulateFormELements() {
        var elementValues = $.cookie('elementValues');
        if (elementValues) {
            Object.keys(elementValues).forEach(function(element) {
                var checked = elementValues[element];
                $("#" + element).prop('checked', checked);
            });
            $("button").text(elementValues["buttonText"])
        }
    }
    $(":checkbox").on("change", function() {
        updateButtonStatus();
        updateCookie();
    });
    $("button").on("click", function() {
        handleButtonClick(this);
        updateCookie();
    });
    $.cookie.json = true;
    repopulateFormELements();
</script>

请告诉我在这种情况下该怎么做。谢谢

它在 Firefox 中工作,只是因为 Firefox 会记住表单输入的状态。如果您希望它在所有浏览器中工作,您可以使用 cookie 来存储选中/未选中的值,或者使用仅用于存储键 => 值对的 localStorage(html5 中的新功能(

您希望在所有复选框上放置 onchange 侦听器,并将值(选中/未选中(存储在 LS 中。

var all_inputs = document.getElementsByTagName("input");
for(var i = 0; i < all_inputs.length; i++)
{
     if( all_inputs[i].getAttribute("type") == "checkbox")
     {
         checkbox = all_inputs[i];
         checkbox.addEventListener("change", function()
         {
             localStorage.setItem(checkbox.getAttribute("name"), ""+checkbox.checked ); // To convert boolean to string i put "" + checkbox.checked
         }
     }
}

但是,如果我们在本地存储中保存了状态,我们还必须在加载页面时更改复选框状态。

var all_inputs = document.getElementsByTagName("input");
document.onload = function()
{
    for(var i = 0; i < all_inputs.length; i++)
    {
         if( all_inputs[i].getAttribute("type") == "checkbox")
         {
             checkbox = all_inputs[i];
             if( (var value = localStorage.getItem(checkbox.getAttribute("name")) != null)
             {
                 if(value == "true")
                     checkbox.checked = true;
                 else if(value == "false")
                     checkbox.checked = false;
             }
         }
    }
}

编辑:所以要包含在脚本标签中的整个代码将是:

document.onload = function()
{
    var all_inputs = document.getElementsByTagName("input");
    document.onload = function()
    {
        for(var i = 0; i < all_inputs.length; i++)
        {
             if( all_inputs[i].getAttribute("type") == "checkbox")
             {
                 checkbox = all_inputs[i];
                 // Change the state (checked/unchecked) if the state is saved in localStorage 
                 if( (var value = localStorage.getItem(checkbox.getAttribute("name")) != null)
                 {
                     if(value == "true")
                         checkbox.checked = true;
                     else if(value == "false")
                         checkbox.checked = false;
                 }
                 // Then put onchange listeners to notify when checkbox state changes in order to save the state in the localStorage
                 checkbox.addEventListener("change", function()
                 {
                     localStorage.setItem(checkbox.getAttribute("name"), ""+checkbox.checked ); // I used : "" + checkbox.checked to convert boolean to string
                 }
             }
        }
    }
}
相关文章: