【问题标题】:How do I serialize the unchecking of checkboxes?如何序列化取消选中复选框?
【发布时间】:2021-05-20 21:03:55
【问题描述】:

我正在尝试使用 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 不同时,它不应该包含检查值 吗?

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

【问题讨论】:

  • 用户前进时复选框的状态没有保存在任何地方?
  • @Twisty 复选框的状态保存在服务器端,但背面的浏览器无法使用。如果选中它,它只会保存在客户端(解决方法是在 DOM 恢复之前取消选中所有框,但这似乎很hacky)。

标签: html jquery dom unobtrusive-ajax


【解决方案1】:

无论您尝试什么浏览器历史操作历史...这里的主要处理是实时保存复选框状态,因此每次 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 sn-ps 中不允许使用localStorage

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多