>本教程演示了如何在网页上制作复选框,即使在页面刷新或浏览器关闭后,他们的检查/未检查状态也是如此。 这是使用浏览器的localStorage
API实现的,可以通过保留用户首选项来增强用户体验。
>该技术对于诸如站点偏好之类的设置特别有用(例如,在新选项卡中打开链接,隐藏元素)。 最后提供了一个演示。
密钥点:
localStorage
在用户浏览器中提供持久存储,即使关闭并重新打开浏览器后,仍保留数据。localStorage
>中。localStorage
适用于非敏感数据;避免存储凭据或个人信息。复选框html:
最初的HTML包含带有关联标签的复选框,分组用于造型容易:
<code class="language-html"><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> <button>Check All</button> </div></code>标签对于可访问性至关重要,允许通过标签单击进行选择。
>
> javaScript(使用jQuery):
> JavaScript处理复选框状态更改,将它们存储在
<code class="language-html"></code>中,然后将它们还原在页面加载:
上
localStorage
<code class="language-javascript">var formValues = JSON.parse(localStorage.getItem('formValues')) || {}; var $checkboxes = $("#checkbox-container :checkbox"); var $button = $("#checkbox-container button"); function allChecked(){ return $checkboxes.length === $checkboxes.filter(":checked").length; } function updateButtonStatus(){ $button.text(allChecked()? "Uncheck all" : "Check all"); } function updateStorage(){ $checkboxes.each(function(){ formValues[this.id] = this.checked; }); formValues["buttonText"] = $button.text(); localStorage.setItem("formValues", JSON.stringify(formValues)); } $checkboxes.on("change", function(){ updateStorage(); updateButtonStatus(); }); function handleButtonClick(){ $checkboxes.prop("checked", allChecked()? false : true); updateStorage(); updateButtonStatus(); } $button.on("click", handleButtonClick); $.each(formValues, function(key, value) { if (key !== "buttonText") { $("#" + key).prop('checked', value); } }); $button.text(formValues["buttonText"]); </code>
检查/取消选中所有功能:
“检查所有”按钮切换所有复选框的状态和更新。
演示:localStorage
>一个工作演示显示持续的复选框行为[此处]
结论:
此方法有效利用
创建持久的复选框,增强用户体验并提供“检查/取消选中”功能的清洁实现。 请记住,不适合敏感数据。 提供的常见问题解答进一步澄清了该技术的各个方面。>
以上是快速提示:持续的复选框检查后的状态后重新加载的详细内容。更多信息请关注PHP中文网其他相关文章!