如何在刷新页面后让复选框保持选中状态?

问题描述 投票:0回答:2

我正在研究如何在刷新页面后保持复选框保持选中状态。 我发现 this 有帮助。 但是,代码不能在我的服务器上正常工作。当我刷新时,复选框保持未选中状态。 我也使用 this 编译器。不好。 See

我使用的代码:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#checkbox-container{
  margin: 10px 5px;
}

#checkbox-container div{
  margin-bottom: 5px;
}

#checkbox-container button{
  margin-top: 5px;
}

input[type=text] {
  padding: .5em .6em;
  display: inline-block;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 3px #ddd;
  border-radius: 4px;
}
</style>
</head>

<body>
<div id="checkbox-container">
  <div>
    <label for="option1">Option 1</label>
    <input type="checkbox" id="option1">
  </div>
  <div>
    <label for="option2">Option 2</label>
    <input type="checkbox" id="option2">
  </div>
  <div>
    <label for="option3">Option 3</label>
    <input type="checkbox" id="option3">
  </div>
</div>
</body>


</html>
<script>
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#checkbox-container :checkbox");
    
    $checkboxes.on("change", function(){
      $checkboxes.each(function(){
        checkboxValues[this.id] = this.checked;
      });
      
      localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });
    
    // On page load
    $.each(checkboxValues, function(key, value) {
      $("#" + key).prop('checked', value);
    });
</script>

在我看来,该代码仅适用于 CODEPEN。 有人可以告诉我出了什么问题吗? 非常感谢。

html checkbox codepen
2个回答
1
投票
<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">
      #checkbox-container {
        margin: 10px 5px;
      }

      #checkbox-container div {
        margin-bottom: 5px;
      }

      #checkbox-container button {
        margin-top: 5px;
      }

      input[type="text"] {
        padding: 0.5em 0.6em;
        display: inline-block;
        border: 1px solid #ccc;
        box-shadow: inset 0 1px 3px #ddd;
        border-radius: 4px;
      }
    </style>
  </head>

  <body>
    <div id="checkbox-container">
      <div>
        <label for="option1">Option 1</label>
        <input type="checkbox" id="option1" />
      </div>
      <div>
        <label for="option2">Option 2</label>
        <input type="checkbox" id="option2" />
      </div>
      <div>
        <label for="option3">Option 3</label>
        <input type="checkbox" id="option3" />
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function () {
        var checkboxValues =
            JSON.parse(localStorage.getItem("checkboxValues")) || {},
          $checkboxes = $("#checkbox-container :checkbox");

        $checkboxes.on("change", function () {
          $checkboxes.each(function () {
            checkboxValues[this.id] = this.checked;
          });

          localStorage.setItem(
            "checkboxValues",
            JSON.stringify(checkboxValues)
          );
        });

        // On page load
        $.each(checkboxValues, function (key, value) {
          $("#" + key).prop("checked", value);
        });
      });
    </script>
  </body>
</html>

您提供的代码有几个问题:

  1. script标签放在HTML body之外。将脚本标签移到正文中或将 JavaScript 代码包装在适当的脚本块中。

  2. 代码中不包含 jQuery 库。要使用 $() 等 jQuery 函数,您需要在使用前包含 jQuery 库。


0
投票

为什么不使用

fieldset
并跟踪整个事物的变化?

  • 没有 jQuery 依赖
  • 简化 HTML
  • 只增加一个听众

我还通用化了侦听器,以便可以轻松修改它以处理更多字段集以及其他

input
类型。
input type="text"
支持作为示例添加。

window.addEventListener("load", (event) => {
    restoreChanges("fieldset1");
    trackChanges("fieldset1");
});

// Reads localStorage back fieldset's inputs 
function restoreChanges(fieldsetId) {
    var json = localStorage.getItem(fieldsetId);
    if(json) {
        JSON.parse(json).forEach(item => {
            if(typeof item.value == "boolean") {
                // Handle checkbox
                document.getElementById(item.id).checked = item.value;
            } else {
                document.getElementById(item.id).value = item.value;
            }
        });
    }
}

// Automatically saves fieldset's inputs to localstorage
function trackChanges(fieldsetId) {
    // Add listener to entire fieldset
    document.getElementById(fieldsetId).addEventListener('change', (event) => {
        var inputValues = [];
        var inputs = event.currentTarget.getElementsByTagName("input");
        Array.from(inputs).forEach(element => inputValues.push(
            {
                type: "input",
                id: element.id,
                value: element.type == "checkbox" ? element.checked : element.value
            }
        ));
        localStorage.setItem(event.currentTarget.id, JSON.stringify(inputValues));
        console.debug(inputValues);
    });
}
<!DOCTYPE html>
<html>
  <body>
    <fieldset id="fieldset1">
        <legend>Choose your options</legend>
        <input type="checkbox" id="option1" />
        <label for="option1">Option 1</label><br/>

        <input type="checkbox" id="option2" />
        <label for="option2">Option 2</label><br/>

        <input type="checkbox" id="option3" />
        <label for="option3">Option 3</label><br/>

        <label for="option4">Option 4</label>
        <input type="text" id="option4" /><br/>
    </fieldset>
  </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.