在我的带有随机复选框数量的php表单中(取决于MySQL查询结果),我使用分页和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);

最佳答案

Cookies具有很小的大小限制,因为它们随每个HTTP请求发送到服务器。使用localStorage或sessionStorage API会更好。这些将数据存储在浏览器内部

尽管localStorage API本身很容易使用,但是有一个非常方便的小库包装程序,您可以使用store.js使其更加简单

参考:MDN STorage Docs

关于javascript - Javascript复选框Cookie,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31457033/

10-10 14:11
查看更多