且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

刷新页面后如何保持单个复选框处于选中状态?

更新时间:2022-01-08 22:04:58

我认为您的代码是在加载表单元素之前执行的,因此请将其放在代码的末尾或使用之前,则不会选择任何内容,因为它尚未加载到DOM中.

I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.

还有一件要做的事情,在您的代码中,该复选框没有任何 id ,因此,由于JSON是使用id值生成的,因此在元素中添加唯一的id以使其起作用.

One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.

<div class="wrap">
  <h3>Background Swap:</h3>
  <form action="" method="POST">
    <div id="checkbox-container">
      Background Swap: <input type="checkbox" id="name" name="new_background" />
    </div>

    <input type="submit" name="submit" value="Upgrade Background" class="button" />
  </form>
  <script>
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function() {
      $checkbox.each(function() {
        checkboxValue[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  </script>
</div>

正在运行的演示: FIDDLE

<script>
  // document ready handler
  // or $(document).ready(Function(){...
  jQuery(function($) {
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function() {
      $checkbox.each(function() {
        checkboxValue[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  });
</script>
<div class="wrap">
  <h3>Background Swap:</h3>
  <form action="" method="POST">
    <div id="checkbox-container">
      Background Swap: <input type="checkbox" id="name" name="new_background" />
    </div>

    <input type="submit" name="submit" value="Upgrade Background" class="button" />
  </form>

</div>

正在运行的演示: FIDDLE