保存切换条件

时间:2017-04-03 11:55:53

标签: javascript php jquery css ajax

我已经为翻转开关编写了一个代码,但状态总是在刷新页面时发生变化:

enter image description here

1 个答案:

答案 0 :(得分:0)

我假设你正在尝试用其他东西替换你的Ajax帖子请求。

我的建议是使用一个cookie,它会在本地保存一些信息供js使用。

首先,添加jQuery&amp; jQuery Cookie在您的网页顶部(在<head>标记内):

<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>

然后,在您的javascript文件中,执行以下操作:

(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);

然后你需要在刷新时检查切换的cookie并添加行为以检查框是否为true:

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

请参阅jsFiddle了解工作示例。

我希望这会有所帮助。