【问题标题】:trigger page reload on specific checkbox selection在特定的复选框选择上触发页面重新加载
【发布时间】:2020-06-19 19:51:21
【问题描述】:

好的,我有一个代码可以将 30 个左右的复选框选择保存到本地存储中,效果很好,我还有一个单独的复选框(如下所示),选中后会自动重新加载页面

<input type="checkbox" id="autoload" class="autoload"> Tick this box to automatically update the results as you choose them from the options below

下面是我必须触发页面重新加载的代码

if ($('#autoload').is(':checked')) {
    location.reload(); 
    }

下面是将复选框保存到本地存储的代码,以及我想在上面添加触发器重新加载代码的地方

window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

我的问题是我不知道在哪里或如何将触发页面重新加载代码放入上面的代码中以使其工作。希望我所有的喋喋不休都有意义,任何帮助都非常感谢。

【问题讨论】:

  • stackoverflow.com/questions/14544104/… 检查此链接我认为这可能有效。
  • .box 复选框和#autoload 复选框之间的关系是什么?
  • .box 是所有复选框的类,#autoload 是触发页面重新加载的复选框的 ID

标签: javascript local-storage


【解决方案1】:

您可以对复选框使用“.change”触发器,如下所示:

window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

$('#autoload').change(() => {
   if ($('#autoload').is(':checked')) {
      location.reload();
   }
});

【讨论】:

  • 我已经尝试了你的建议,但不幸的是,它似乎不起作用:(
  • 有人对我如何排序有任何其他想法吗?
【解决方案2】:

自己整理的

window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
      if ($('#autoload').is(':checked')) {
         location.reload()
      };
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多