如何在localStorage中保存复选框值?

时间:2014-06-11 00:16:31

标签: jquery checkbox local-storage

我一直在关注在localStorage中保存复选框值,我在这里找到了一些主题,但我仍然遇到问题。

以下是我的 HTML 的一部分,用于创建复选框:

<div id="displayer_show">
    <div class="demo" id="labels2-3">
        <input name="switch_show" type="checkbox" value="1" checked/>
     </div>
</div>

我的主要脚本的一部分:

$(function () {
    var data = localStorage.getItem("showning");
    if (data !== null) {
        $("input[name='switch_show']").attr("checked", "checked");
    }
});

$("input[name='switch_show']").click(function () {

    if ($(this).is(":checked")) {
        localStorage.setItem("showning", $(this).val());
    } else {
        localStorage.removeItem("showning");
    }
});

有jsfiddle链接:http://jsfiddle.net/remibenault/Dp4Tj/8/

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

编辑脚本如下:

$(function () {
  var data = localStorage.showning;
  $("input[name='switch_show']")
    .prop('checked',data=='true')
    .change(function () {
       localStorage.showning = $(this).prop("checked");
    });
});

问题是默认选中复选框,而你

答案 1 :(得分:1)

只需删除value="1" checked部分就可以了。 $(this).val()也应为1。我不太清楚你为什么打电话给$(this).val()

http://jsfiddle.net/prankol57/Dp4Tj/9/

相关问题