Javascript Checkbox cookie

时间:2015-07-16 14:25:44

标签: javascript php jquery cookies checkbox

在我的php表单上随机数量的复选框(取决于MySQL查询结果)我使用pagination和checkbox_cookie.js脚本来记住来自其他子页面的复选框值。

如果有少于200个复选框,那么它会失效,因为它会丢失最后一个复选框更改的内存,例如我有8个子页面中的230个复选框,它记住7个子页面中的位置,但无法保存第8页的复选框状态。

现在我真的不明白为什么会这样。

是cookie大小吗? JSON数组限制?什么东西? 也许你会知道在哪里寻找一个aswer。

这是checkbox_cookie代码:

var aa_checkbox;  

function init_checkbox(){  
//setup blank cb cookie  
if(!Cookie.read('cb')){  
Cookie.write('cb', JSON.encode({}));  
}  

//setup "associative array" to match what is currently in the cookie  
aa_checkbox = JSON.decode(Cookie.read('cb'));  


//set up each checkbox with class="remember_cb"  
$$('input.remember_cb').each(function(el){  

//mark checked if it is in the cookie  
if(aa_checkbox[el.name]){  
  el.checked = 'checked'  
}  

//setup onclick event to put checkbox status in the   
el.addEvent('change', function(){  
  if(el.checked){  
    aa_checkbox[el.name] = 1;
  }else{  
    delete(aa_checkbox[el.name]);
  }     
})  
})  

//save aa_checkbox back into cookie upon leaving a page  
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};  

setup_form();  

return true;  
 }  

function setup_form(){  
 //set up form so that it adds the inputs upon submit.  
$$('form.remember_cb_form').each(function(form){  
 form.addEvent('submit', function(ev){  
   //clean up previously inserted inputs  
   var aa_hidden_insert = $$('input.hidden_insert');  
    $each(aa_hidden_insert, function(el){   
     el.parentNode.removeChild(el);  
   })  

   var el_form = this;  

    //insert hidden elements representing the values stored in  aa_checkbox  
  $each(aa_checkbox, function(i_value, s_name){  
    if(i_value){   
      var el_input = document.createElement('input');  
      el_input.type = 'hidden';  
      el_input.value = i_value;  
      el_input.name = s_name;  
      el_input.setAttribute('class', 'hidden_insert');  
      el_form.appendChild(el_input);  
    }  
  });  
   });  
 });  
}  

window.addEvent('domready', init_checkbox); 

1 个答案:

答案 0 :(得分:1)

Cookie的大小限制非常小,因为它们会随每个http请求一起发送到服务器。使用localStorage或sessionStorage API会更好。这些在浏览器本身中存储数据

虽然localStorage API在它自己的使用上相当简单,但是有一个非常方便的小库包装器,你可以使用store.js使它更简单

参考:MDN STorage Docs