【问题标题】:How to Keep checkbox checked after refresh the page刷新页面后如何保持复选框选中
【发布时间】:2014-04-03 05:35:36
【问题描述】:

我有一个下拉框,当从下拉列表中选择时,它会显示数据。 另外我在每个 td 上方都有一个复选框,用于隐藏由 java 脚本执行的列,如果用户选中该复选框并在下拉框中选择另一个值,则所选复选框将不会显示。

下面是选中复选框时隐藏列的代码

我想测试用户是否选中了复选框并且他在下拉框中选择了另一个值,那么所选的复选框将不会显示任何一个 我怎么能这样?

<input type='checkbox' style='margin:-19px 0 0 732px;   border: 1px solid grey;' name='9xx'/>9xx
<input type='checkbox' style='margin:-19px 0 0 36px;   border: 1px solid grey;' name='6xx'/>6xx  
<input type='checkbox' style='margin:-19px 0 0 30px;   border: 1px solid grey;' name='12xx'/>12xx
<input type='checkbox' style='margin:-19px 0 0 21px;   border: 1px solid grey;' name='14xx'/>14xx
<input type='checkbox' style='margin:-19px 0 0 26px;   border: 1px solid grey;' name='10xx'/>10xx
<input type='checkbox' style='margin:-19px 0 0 31px;  border: 1px solid grey;' name='8xx'/>8xx
<input type='checkbox' style='margin:-19px 0 0 31px;  border: 1px solid grey;' name='11xx'/>11xx

<script>
$("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).show();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});

</script>

【问题讨论】:

  • 将复选框的状态放入cookie中,并在页面加载时使用它来初始化复选框。
  • @Barmar 为什么人们仍然想在这些事情上使用 cookie。我认为我们应该开始使用localStorage

标签: javascript php jquery html checkbox


【解决方案1】:

使用 localStorage

这是它的 JSFiddle 示例。 Link

背后的代码:

HTML 代码:

<input type="checkbox">

JS代码:

$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('input').prop('checked', test || false);
});

$('input').on('change', function() {
    localStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});

【讨论】:

  • 此解决方案将检查该页面上所有可用的checkboxes,即使您选择了一个复选框。
  • 是的,我知道。但是任何熟悉 jQuery 的人都可以为单个复选框编辑此代码 :) 这并不难。
猜你喜欢
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多