【问题标题】:Jquery prop on checkbox doesn't work on page load复选框上的 Jquery 道具在页面加载时不起作用
【发布时间】:2016-07-26 21:07:20
【问题描述】:

我的页面中有一个默认选中的复选框。如果用户更改它,我会尝试使用 LocalStorage 并将值保存在那里。

这就是我所做的:

<script language="javascript" type="text/javascript">
        jQuery(document).ready(function ($) {

            $('#togglelist').prop('checked', localStorage.ListCheckbox);

            $("#togglelist").change(function () {
                localStorage.ListCheckbox = $('#togglelist').prop('checked');
            });

    </script>

我可以在开发者控制台上看到值在单击复选框时发生变化。另外,如果我不选中它(false),在下一页加载时,本地存储的值为 false,但复选框仍处于选中状态。

编辑:我不能使用checkboxradio('refresh'),因为我没有 JQM。

【问题讨论】:

  • $('#togglelist').prop('checked', localStorage.ListCheckbox==='true');
  • 天哪。就是这个。您可以将其添加为答案吗?
  • 因为non-empty字符串总是真实的,localStorage总是以string的形式存储数据

标签: javascript jquery checkbox


【解决方案1】:

由于non-empty 字符串始终为真,localStorage 始终以string 的形式存储数据

string测试localStorage的值

$('#togglelist').prop('checked', localStorage.ListCheckbox==='true');

【讨论】:

  • 9分钟内接受答案(由于SE的限制)
猜你喜欢
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
相关资源
最近更新 更多