【问题标题】:Keep last checkbox checked after page refresh页面刷新后保持最后一个复选框处于选中状态
【发布时间】:2016-06-02 11:28:33
【问题描述】:

我有 6 个复选框,我需要最后一个被选中的复选框,以便在页面刷新后保持选中状态。

我现在拥有的是保留所有选中的复选框,在页面刷新后检查。

关于如何编辑它以获得所需结果的任何想法?

这是我当前的代码:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Persist checkboxes 1</title>
  </head>

  <body>

      <input type="checkbox" id="option1">

      <input type="checkbox" id="option2">

      <input type="checkbox" id="option3">

      <input type="checkbox" id="option4">

      <input type="checkbox" id="option5">

      <input type="checkbox" id="option6">


    <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>
      $(":checkbox").on("change", function(){
        var checkboxValues = {};
        $(":checkbox").each(function(){
          checkboxValues[this.id] = this.checked;
        });
        $.cookie('checkboxValues', checkboxValues, { expires: 1, path: '/' })
      });

      function repopulateCheckboxes(){
        var checkboxValues = $.cookie('checkboxValues');
        if(checkboxValues){
          Object.keys(checkboxValues).forEach(function(element) {
            var checked = checkboxValues[element];
            $("#" + element).prop('checked', checked);
          });
        }
      }

      $.cookie.json = true;
      repopulateCheckboxes();
    </script>
  </body>
</html>

【问题讨论】:

  • 因此,如果用户选择了 3 个复选框,您只希望在刷新后保留他们选择的 last 复选框,对吗?
  • @jeffdill2 是的,正确。
  • 刷新如何?通过单击页面控件或浏览器刷新按钮
  • 您这里的代码目前是否有效?我问是因为您为您的change 事件定位#option id,但您的input 元素都不会匹配该选择器,因为它们都是#option1#option2 等。
  • @SkyWookie,如果他们先选中底部的复选框,然后然后选中顶部的复选框,则不会起作用。

标签: javascript jquery html checkbox


【解决方案1】:

如果您只想保留最后一个选中的复选框,而不是遍历所有复选框并将它们存储在 cookie 中,只需在每次选中复选框时使用 id 覆盖 cookie选中,然后您的 cookie 中将始终保留最新的 id

<script>
  $("[id^=option]").on("change", function() {
    if ($(this).prop('checked')) { // This will make sure an ID isn't stored if a checkbox is unchecked.
      $.cookie('checkboxId', this.id, { expires: 1, path: '/' });
    }
  });

  function repopulateCheckboxes() {
    var checkboxId = $.cookie('checkboxId');

    if (checkboxId) {
      $("#" + checkboxId).prop('checked', checked);
    }
  }

  $.cookie.json = true;
  repopulateCheckboxes();
</script>

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2014-08-29
    • 2013-01-21
    • 2011-03-11
    相关资源
    最近更新 更多