保持复选框结果相同,即使刷新页面也是如此

时间:2017-07-27 14:10:01

标签: javascript

此代码的输出由图像显示。即使在页面刷新后如何保持相同的结果。换句话说,当一次按钮单击时,如果页面刷新,我怎么能保持相同的结果呢?

<style>
    #cb3.highlight .label {background-color:yellow;}
        #cb2.highlight .label {background-color:green;}
        #cb1.highlight .label  {background-color:red;}
    </style>
    <script>
    var checked = [];

        $(document).ready(function() {
            if (localStorage.getItem("checked") == null)
                localStorage.setItem("checked", checked);

            $("#Table input").click(function() {
                if ($(this).is(":checked")) {
                    $(this).parent().parent().addClass("highlight");
                    checked.push($(this).attr("id"));
                } else {
                    $(this).parent().parent().removeClass("highlight");
                    checked.remove($(this).attr("id"));
                }
                localStorage.setItem("checked", JSON.stringify(checked));
            });

            var saved = JSON.parse(localStorage.getItem("checked"));
            for (var i = 0;i < saved.length; i++) {
                var itemAtIndex = $("#" + saved[i] + "");
                itemAtIndex.click();
                itemAtIndex.parent().parent().addClass("highlight");
            }
        });
    </script>
    <div class="col-lg-10">

    <table id="Table" border="1">
          <tr id="cb1">
            <td><input type="checkbox" name="cb1" value="y" /></td>
            <td class=label>Click me</td>
        </tr><tr id="cb2">
            <td><input type="checkbox" name="cb2" value="y" /></td>
            <td class=label>Click me</td>
        </tr>
        <tr id="cb3">
            <td><input type="checkbox" name="cb3" value="y" /></td>
            <td class=label>Click me</td>
        </tr>
      </table>
    </div>

输出 enter image description here

0 个答案:

没有答案