weixin_33726318 2017-04-03 11:55 采纳率: 0%
浏览 19

保存切换条件

I have written a code for the flip switch but the state always changes while refreshing the page:

enter image description here

  • 写回答

1条回答 默认 最新

  • weixin_33747129 2017-04-03 12:09
    关注

    I'll assume you are trying to replace the Ajax post request you have with something else.

    My suggestion would be to use a cookie which will save some information locally for js to use.

    Firstly, add jQuery & jQuery Cookie to the top of your webpage like this (within the <head> tag):

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js.js" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js.js" charset="utf-8"></script>
    

    Then, in your javascript file, do the following:

    (function($) {
      // Grabs cookie and puts into a js variable.
      var toggled = $.cookie('toggled');
    
    //  On click of checkbox, check if set/unset. Then set cookie to true/false.
    
      $('#switch').change(function()) {
          if($(this).is(':checked')) { // If set to true, set toggled to true.
            $.cookie('toggled', true, { expires: 1, path: '/' });
          } else { // Else, set to false.
            $.cookie('toggled', null, { expires: 1, path: '/' });
          }
      }
    
    })(jQuery);
    

    You'll need to then check the toggled cookie on refresh and add behaviour to check the box if toggled is true:

    if(toggled == 'true') { //If cookie set to true...
     $('#switch').attr('checked','checked').flipswitch("refresh") // Flip the switch (Important for jquery mobile).
    }
    

    Please see jsFiddle for a working example.

    I hope this helps.

    评论

报告相同问题?