首页 > 解决方案 > localStorage 为复选框返回错误值

问题描述

我正在使用本地存储来恢复数据,以防用户意外重新加载页面,但是当他们重新加载一个复选框时,即使他们没有选中它也是如此。

下面是我的代码,唯一呈现的错误值是复选框。我还有其他字段,在重新加载页面时,正在恢复的值是准确的。

我想我错过了一两件事,任何帮助将不胜感激。谢谢。

var remember_state = {
name: "rememberState",
clearOnSubmit: true,
_defaultNoticeDialog: function() {
  return $("<p />", { "class": "remember_state" })
    .html('Restore previously entered information? <a class="btn btn-sm btn-link" href="#"><i class="mrx far fa-history"></i>Restore</a>');
},
noticeConfirmSelector: "a",
noticeSelector: ".remember_state",
use_ids: false,
objName: false,
restoreState: function(e) {
  var data = JSON.parse(localStorage.getItem(this.objName)),
      $f = this.$el,
      $e;
  for (var i in data) {
    $e = $f.find("[name=\"" + data[i].name + "\"]");
    if ($e.is(":radio")) {
      $e.filter("[value=\"" + data[i].value + "\"]").prop("checked", true);
    }
    else if ($e.is(":checkbox") && data[i].value) {
      $e.prop("checked", true);
    }
    else if ($e.is("select")) {
      $e.find("[value=\"" + data[i].value + "\"]").prop("selected", true);
    }
    else {
      $e.val(data[i].value);
    }
    $e.change();
  }
  this.noticeDialog.remove();
  e && e.preventDefault && e.preventDefault();
},
cancelNotice: function(e) {
  e.preventDefault();
  this.noticeDialog.remove();
},
chooseStorageProp: function() {
  if (this.$el.length > 1) {
    if (console && console.warn) {
      console.warn("WARNING: Cannot process more than one form with the same" +
        " object. Attempting to use form IDs instead.");
    }
    this.objName = this.$el.attr("id");
  }
},
errorNoID: function() {
  if (console && console.log) {
    console.log("ERROR: No form ID or object name. Add an ID or pass" +
      " in an object name");
  }
},
saveState: function(e) {
  var instance = e.data.instance;
  var values = instance.$el.serializeArray();
  // jQuery doesn't currently support datetime-local inputs despite a
  // comment by dmethvin stating the contrary:
  // http://bugs.jquery.com/ticket/5667
  // Manually storing input type until jQuery is patched
  instance.$el.find("input[type='datetime-local']").each(function() {
    var $i = $(this);
    values.push({ name: $i.attr("name"), value: $i.val() });
  });
  values = instance.removeIgnored(values);
  values.length && internals.setObject(instance.objName, values);
},
save: function() {
  var instance = this;
  if (!this.saveState) {
    instance = this.data(remember_state.name);
  }
  instance.saveState({ data: { instance: instance } });
},
bindNoticeDialog: function() {
  if (!this.noticeDialog || !this.noticeDialog.length || !this.noticeDialog.jquery) {
    this.noticeDialog = this._defaultNoticeDialog();
  }
  this.noticeDialog.on("click." + this.name, this.noticeConfirmSelector, $.proxy(this.restoreState, this));
  this.noticeDialog.on("click." + this.name, this.noticeCancelSelector, $.proxy(this.cancelNotice, this));
},
setName: function() {
  this.objName = this.objName || this.$el.attr("id");
  if (!this.objName) { this.errorNoID(); }
},
init: function() {
  this.bindNoticeDialog();
  this.setName();

  if (!this.objName) { return; }

  this.bindResetEvents();
  this.createNoticeDialog();

  $(window).bind("unload." + this.name, { instance: this }, this.saveState);
}

};

编辑:我console.logfor循环中做了 a 并且console.log(data.value[i])at的值$e.is(":checkbox")0

标签: javascriptjquery

解决方案


我们正在使用 jquery 库jquery_remember_state,我的问题是他们有一个错误,即使它们具有不同的值,相似名称的复选框也会返回相同的值。我们正在使用 simple_form 并且它添加了一个隐藏值,checkbox因此在尝试恢复状态时它会给我们带来错误。

我必须做出的改变是这样的:

if ($e.is(":checkbox") && data[i].value) {
          $e = $e.filter("[value=\"" + data[i].value + "\"]");
          if ($e.length) {
            $e.prop("checked", true);
          }
        }

这是包含完整代码的文件,以防有人遇到此问题:

https://github.com/RepairShopr/jquery_remember_state/blob/multiple-checkboxes/source/javascripts/jquery.remember-state.js


推荐阅读