簡體   English   中英

頁面刷新后保持選中最后一個復選框

[英]Keep last checkbox checked after page refresh

我有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>

如果您只想保留所選的最后一個復選框,而不是遍歷所有復選框並將其存儲在cookie中,則只需在每次選中id為所選內容的復選框時覆蓋cookie,然后您始終將最新id保留在您的Cookie中:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM