php - 重新加载时保存复选框状态

标签 php jquery html session

如何通过 session 保存复选框状态?我正在使用这个 jquery 代码来切换选项:

$('div.check input:checkbox').bind('change',function(){
    $('#'+this.id+'txt').toggle($(this).is(':checked'));
});

但是当我重新加载时,复选框恢复到默认状态。我知道我必须使用 session ,但是如何使用 php 中的 session 使复选框状态持续存在?

html:

<div class="check">
<p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>  
<p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
    </div>

    <div id="nametxt"> Show Name TEXT </div>
    <div id="reftxt"> Show Ref TEXT </div>

最佳答案

纯 JavaScript 支持 localStorage(如果可用),否则使用 document.cookie

function getStorage(key_prefix) {
    // this function will return us an object with a "set" and "get" method
    // using either localStorage if available, or defaulting to document.cookie
    if (window.localStorage) {
      // use localStorage:
      return {
        set: function(id, data) {
          localStorage.setItem(key_prefix+id, data);
        },
        get: function(id) {
          return localStorage.getItem(key_prefix+id);
        }
      };
    } else {
      // use document.cookie:
      return {
         set: function(id, data) {
           document.cookie = key_prefix+id+'='+encodeURIComponent(data);
         },
         get: function(id, data) {
           var cookies = document.cookie, parsed = {};
           cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
              parsed[key] = decodeURIComponent(value);
           });
           return parsed[key_prefix+id];
         }
       };
     }
  }

jQuery(function($) {
  // a key prefix is used for the cookie/storage
  var storedData = getStorage('com_mysite_checkboxes_'); 

  $('div.check input:checkbox').bind('change',function(){
    $('#'+this.id+'txt').toggle($(this).is(':checked'));
    // save the data on change
    storedData.set(this.id, $(this).is(':checked')?'checked':'not');
  }).each(function() {
    // on load, set the value to what we read from storage:
    var val = storedData.get(this.id);
    if (val == 'checked') $(this).attr('checked', 'checked');
    if (val == 'not') $(this).removeAttr('checked');
    if (val) $(this).trigger('change');
  });

});

jsFiddle demo available -- 单击一些复选框,然后再次“运行”脚本!

关于php - 重新加载时保存复选框状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3313595/

相关文章:

php - 将 CSS 类应用于动态表格数据

php - 无法在 php 中使用 css 设置表格样式

php - 将两列分组并不同

PHP 将动态部分/表格添加到 word 模板

javascript - 将 html(文本)转换为 jQuery 对象 : lost value

javascript - 使用 jQuery 插入 HTML 页面的第一个项目缺少结束标记

javascript - 查找最近的相似 sibling

java - 使用 StringBuilder 时转义引号

javascript - 如何找到类为 "select"的 attr

jquery - 如何画一个圆圈来表示在html中的选择