如何序列化取消选中复选框?

问题描述

我正在尝试使用 unobtrusive-ajax 来允许站点在 JavaScript 可用时将其内容更新为 AJAX,否则将其更新为静态页面。我想支持浏览器的 Back 按钮在历史记录中向后移动。

用户浏览网站时,我使用 JavaScript 的历史 API 来操纵浏览器历史记录。我将 HTML(通过 innerHTML)和 DOM 的当前状态(通过 JQuery 的 serialize 方法)存储在历史对象中。当用户点击 Back 时,HTML 和 DOM 分别从缓存的 HTML 和序列化的 DOM 中恢复。

但是,我丢失了有关在页面加载 ("checked"="checked") 时选中但用户未选中的复选框的信息。

根据 https://api.jquery.com/serialize/ 处的 JQuery 文档

来自复选框和单选按钮(“radio”或“checkBox”类型的输入)的值仅在被选中时才包含在内。

此处的“值”指的是选中状态,而不是复选框的 value

这是设计错误吗? 当它不同于 HTML 时,它不应该包含选中的值吗?

其他元素是否有条件序列化的其他属性

解决方法

无论您尝试什么浏览器历史操作历史...这里的主要内容是实时保存复选框状态,以便每次 JS 运行时,您都可以检索保存的值。

可以通过 localStorage 保存复选框的状态。

下面的内容在页面重新加载时完美运行。您的历史操作应该绕过后退按钮的“正常”行为,而不是再次运行 JS。我把它留给你。 ;)

// Check box state array
let checkboxesState = []

// If that is the very first page load and there is no local storage.
if(localStorage.getItem("checkedCheckboxes") === null){

  $("input[type='checkbox']").each(function(index){
    checkboxesState.push(this.checked)

    // Add a data attribute for the index of the checkbox
    this.setAttribute("data-chk_index",index)
  })
  // Save
  localStorage.setItem("checkedCheckboxes",JSON.stringify(checkboxesState))
}

// If there already is a checkbox state storage
else{
  checkboxesState = JSON.parse(checkboxesState)
  
  $("input[type='checkbox']").each(function(index){
    this.checked = checkboxesState[index]

    // Add a data attribute for the index of the checkbox
    this.setAttribute("data-chk_index",index)
  })
}

// Update the array on click
$("input[type='checkbox']").on("click",function(){
  checkboxesState[this.getAttribute("data-chk_index")] =  this.checked
  
  // Update Storage
  localStorage.setItem("checkedCheckboxes",JSON.stringify(checkboxesState))
  
  // That is the current state of the saved array
  console.log(localStorage.getItem("checkedCheckboxes"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">

检查我的 CodePen,因为 SO 片段中不允许使用 localStorage

,

JQuery 的 serialize 用于序列化表单以提交给服务器,除非另有说明,否则假定复选框未被选中。

问题在于 https://github.com/kflorence/jquery-deserialize/ 中的 deserialize 在应用序列化字符串中的属性之前没有清空这些属性。

我通过在应用反序列化之前取消选中所有复选框来解决这个问题。

document.getElementById("thepage").innerHTML = stateHtml;
$("#thepage input[type='checkbox']").prop("checked",false);
$("#thepage").deserialize(stateDomSerialized);