如何在使用javascript刷新页面后记住点击的按钮?

Dus*_*hee 0 javascript

以下代码用于在单击复选框时突出显示表记录.但是一旦我刷新了页面,突出显示的记录就会消失.如果页面刷新后我怎么能保持相同的突出显示记录?

<style>
    .highlight {
       background-color: yellow;
    }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        $("#Table input").click(function() {
            if ($(this).is(":checked")) {
                $(this).parent().parent().addClass("highlight");
            } else {
                $(this).parent().parent().removeClass("highlight");
            }
        });
    });
    </script>
    <body>
    <div class="col-lg-10">
    <form name="f">
    <table id="Table" border="1"><tr>
        <td><input type="checkbox" name="cb1" id="cb1" value="y" /></td>
        <td>Click me</td>
    </tr><tr>
        <td><input type="checkbox" name="cb2" id="cb2" value="y" /></td>
        <td>Click me</td>
    </tr><tr>
        <td><input type="checkbox" name="cb3" id="cb3" value="y" /></td>
        <td>Click me</td>
    </tr></table>
    </div>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

sta*_*eth 5

您必须将状态保存在某个位置,可以在URL中作为查询字符串,也可以使用浏览器localStorage.然后在页面加载时,检查该状态并相应地突出显示.

尝试这样的事情:

$("#Table input").click(function() {
    if ($(this).is(":checked")) {
        if(!localStorage.checked) {
            localStorage.checked = [];
        }
        localStorage.checked.push($(this));
        $(this).parent().parent().addClass("highlight");
    } else {
        for (var i = 0;i < localStorage.checked.length; i++) {
            var itemAtIndex = localStorage.checked[i];
            if(itemAtIndex == $(this)){
                localStorage.splice(i, 1);
            }
        }
        $(this).parent().parent().removeClass("highlight");
    }
});


//on page load
for (var i = 0;i < localStorage.checked.length; i++) {
    var itemAtIndex = localStorage.checked[i];
    itemAtIndex.parent().parent().addClass("highlight");
}
Run Code Online (Sandbox Code Playgroud)