简体   繁体   English

在JQuery中包括未检查状态

[英]Including Unchecked State in JQuery

So I am not a programmer, but I can understand things and can follow directions fairly well. 因此,我不是程序员,但我可以理解并可以很好地遵循指示。

I implemented some JS I found on JSfiddle to save the state of checkboxes, and it works great. 我实现了一些在JSfiddle上找到的JS,以保存复选框的状态,并且效果很好。 You check it, it stays checked on refresh. 您检查它,它在刷新时保持选中状态。

The problem though, if you uncheck a box and refresh, it comes back checked. 但问题是,如果您取消选中某个框并刷新,则会重新检查它。 This is the Fiddle I used: JS Fiddle for Saving Checked State with Cookies 这是我使用的小提琴: JS小提琴,用于保存Cookie的检查状态

//===== Cookies Plugin=====   //

(function ($) {

        $.cookie = function (key, value, options) {

            // key and at least value given, set cookie...
            if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
                options = $.extend({}, options);

                if (value === null || value === undefined) {
                    options.expires = -1;
                }

                if (typeof options.expires === 'number') {
                    var days = options.expires, t = options.expires = new Date();
                    t.setDate(t.getDate() + days);
                }

                value = String(value);

                return (document.cookie = [
            encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
            }

            // key and possibly options given, get cookie...
            options = value || {};
            var decode = options.raw ? function (s) { return s; } : decodeURIComponent;

            var pairs = document.cookie.split('; ');
            for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
                if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
            }
            return null;
        };
    })(jQuery);

//======================================//

  $(document).ready(function () {

        var checkbox = $('#boxlawreg').find(':checkbox'), checkboxCookieName = 'checkbox-state';

        checkbox.each(function () {
            $(this).attr('checked', $.cookie(checkboxCookieName + '|' + $(this).attr('name')));
        });

        checkbox.click(function () {                
            $.cookie(checkboxCookieName + '|' + $(this).attr('name'), $(this).prop('checked'));
        });
    });

Can anybody assist with how to make it work for checked and unchecked states? 有人可以协助如何使其在已检查和未检查状态下工作吗?

Somebody at work helped me by giving me this code, which works (note the classes for Input) 工作中的某人通过给我这个代码来帮助我,该代码可以正常工作(请注意Input类)

    // Avoid scoping issues by encapsulating code inside anonymous function
(function() {
  // variable to store our current state
  var cbstate;

  // bind to the onload event
  window.addEventListener('load', function() {
    // Get the current state from localstorage
    // State is stored as a JSON string
    cbstate = JSON.parse(localStorage['CBState'] || '{}');

    // Loop through state array and restore checked 
    // state for matching elements
    for(var i in cbstate) {
      var el = document.querySelector('input[name="' + i + '"]');
      if (el) el.checked = true;
    }

    // Get all checkboxes that you want to monitor state for
    var cb = document.getElementsByClassName('save-cb-state');

    // Loop through results and ...
    for(var i = 0; i < cb.length; i++) {

      //bind click event handler
      cb[i].addEventListener('click', function(evt) {
        // If checkboxe is checked then save to state
        if (this.checked) {
          cbstate[this.name] = true;
        }

    // Else remove from state
        else if (cbstate[this.name]) {
          delete cbstate[this.name];
        }

    // Persist state
        localStorage.CBState = JSON.stringify(cbstate);
      });
    }
  });
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM