HTML5 localStorage在Checkbox上执行操作

时间:2013-03-04 17:46:53

标签: jquery html5

按照此处的教程http://css-tricks.com/video-screencasts/96-localstorage-for-forms/。我能够使用提交按钮重新创建功能,但是,而不是按钮,是否可以使用复选框?

这是我到目前为止所拥有的,

if (localStorage) {

$(function() {

    // Insert new buttons
    $("#savelinks")
        .after("<input type='submit' value='Save Address' id='saveData'> &nbsp;&nbsp;")
        .after("<input type='submit' value='Clear Saved Address' id='clearData'>");

    $("#saveData")
        .click(function(e) {

                    e.preventDefault();
                    // Test if saved data exists on page load
                    localStorage.setItem("flag", "set");
                    var data = $("#form1").serializeArray();

                    // iterate over results
                    $.each(data, function(i, obj) {

                                   localStorage.setItem(obj.name, obj.value);

                     });

        });



    if (localStorage.getItem("flag") == "set") {
        var data = $("#form1").serializeArray();
        $.each(data, function(i, obj) {
            $("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
        });
    }   



    $("#clearData")
        .click(function(e) {
            e.preventDefault();
            localStorage.setItem("flag", "");
        });
});
}

提前谢谢!

1 个答案:

答案 0 :(得分:0)

使用change事件,看看是否选中了复选框;

$('#MyCheckbox').change(function() {

  var $this = $(this), // Current checkbox
      isChecked = this.checked, // We can also use $this.prop('checked')
      data = $('#form1').serializeArray();

  if (isChecked) {
    // Store serialized form data
  } else {
    // Clear stored form data
  }

});